Leetcode (DoorDash)

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Design File System You are asked to design a file system that allows you to create new paths and associate them with different values. The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, "/leetcode" and "/leetcode/problems" are valid paths while an empty string "" and "/" are not. Implement the FileSystem class: - bool createPath(string path, int value) Creates a new path and associates a value to it if possible and returns true. Returns false if the path already exists or its parent path doesn't exist. - int get(string path) Returns the value associated with path or returns -1 if the path doesn't exist.

Classic prefix trie. Only note is that last path item has a check on the value since we don't want to overwrite path values. See if you can code this quickly. Also conditional check if the path is already there. The hard part I think is knowing when to write when adding the path checking n-1 path.

Koko Eating Bananas Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return the minimum integer k such that she can eat all the bananas within h hours.

Binary search 1 to max piles as speed. If its feasible, which is the sum of the pile divide by the speed and its ceiling of that is less than max cap h then right = mid otherwise left

Check if One String Swap Can Make Strings Equal You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.

Check if they are equal first. Then we check the diff count, needs to be exactly 2. Then we iterate through, find the diff at i then we scan forward looking for a letter that matches it. S1[i] == S2[j] and S1[j] == S2[i]

You are given an m x n grid rooms initialized with these three possible values. -1 A wall or an obstacle. 0 A gate. INF Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

Classic BFS. I fumbled with TLE here because before adding to the queue we should check if the new cells value is greater than the current ones cell + 1. Then we update its value after appending to the queue.

Minimum Number of Steps to Make Two Strings Anagram You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. An Anagram of a string is a string that contains the same characters with a different (or the same) orderi

Keep a counter of letters of S. Loop through the letters of T and decrement from the counter. If it is 0 or less, we know that letter needs to be replaced (not in s) increment count by 1.

Max Area of Island You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the island. Return the maximum area of an island in grid. If there is no island, return 0.

Straightforward BFS. Just remember to mark the node as 0 when searching and before appending to queue and incrementing the island size.

Find Nearest Point That Has the Same X or Y Coordinate You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1. The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).

Straightforward, go through each point, skip if they don't share an x or y, calculate the manhattan distance. If its smaller, record that and its index. Then at end just return the index if there else -1.

Binary Tree Maximum Path Sum A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path.

Let's do this recursively. We want to get the max on the left, the max on the right and then we want to calculate the current sum. max_on_left + node.val + max_on_right. Then the max there is what we want to update our answer too. After that, we return only one chain, so the current nodes value + the max on the left OR the max on the right.

Asteroid Collision We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

Stack. Interesting is the else in the while loop. but pretty much the logic is straightforward. Push into the stack if there's no collisions (different signs) or empty stack

Number of Distinct Islands You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other. Return the number of distinct islands.

iterate through do a dfs if its a 1. Keep a visited set. Record the direction path strings. and store it. Return that length.

Design In-Memory File System Design a data structure that simulates an in-memory file system. Implement the FileSystem class: FileSystem() Initializes the object of the system. List<String> ls(String path)If path is a file path, returns a list that only contains this file's name.If path is a directory path, returns the list of file and directory names in this directory.The answer should in lexicographic order. void mkdir(String path) Makes a new directory according to the given path. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well. void addContentToFile(String filePath, String content)If filePath does not exist, creates that file containing given content.If filePath already exists, appends the given content to original content. String readContentFromFile(String filePath) Returns the content in the file at filePath.

A file system implemented via using a tree and nodes. Basically you want to create notes where theres a sorted dictionary as its children and content if its a file. The caveat here to know is that if we call ls on a file just check if theres content return that path[-1] otherwise just return the keys of the children. Rest of the behavior is just like a prefix tree.

Count all Valid Pickup and Delivery Options Given n orders, each order consists of a pickup and a delivery service. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7.

Alright, so for the pickups, there are N! options. Think about. Imagine like P1, P3, P4, P2 etc.... Now thinking about where the deliveries can go. D2 has to go after P2 (only 1 option): P1 P3 P4 P2, D2 D4 has 3 options it can be after D2, after P2 or after P4. Following that you end up with 1 * 3 * 5 * 7 which is 2i - 1 think like 2, 4, 6, 8. The answer then is the choices for pick times the choices for deliveries. Also option for creating them all is there.

Path with Maximum Minimum Value Given an m x n integer matrix grid, return the maximum score of a path starting at (0, 0) and ending at (m - 1, n - 1) moving in the 4 cardinal directions. The score of a path is the minimum value in that path. For example, the score of the path 8 → 4 → 5 → 9 is 4.

BFS with a max heap. Pretty much starting at 0,0 and max heap. keep updating the min we see, break out if we're in bottom right, check four directions and push in the heap. We keep taking the max value path.

289. Game of Life According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.

Count the live neighbors at every direction for every cell. If we have a cell that is 1 alive and <2 or >3 live neighbors. Then mark as -1 for kill. If its dead and exactly 3 live neighbors then mark as 2 to bring it to live. While checking for live neighbors we can use abs value to figure out the same for value and marking. Then final loop just do conversions of 2 to 1 and -1 to 0.

838. Push Dominoes There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where: dominoes[i] = 'L', if the ith domino has been pushed to the left, dominoes[i] = 'R', if the ith domino has been pushed to the right, and dominoes[i] = '.', if the ith domino has not been pushed. Return a string representing the final state.

Create a left distance and right distance arrays. Basically each index represents the closest left or closest right. If R its 0 otherwise just 1 + the previous same with left. The we loop through, basically if its a letter leave it be. But if its a period, we check the smaller value of rdist and ldist and append that value. If its the same leave a period to represent conflict.

LRU Cache Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. The functions get and put must each run in O(1) average time complexity.

Dictionary and doubly linked list. Each node has key and value. When we do gets, get the node from cache/dictionary move it to the front and return the value. When we push, throw it in the front and add the key -> node to dictionary. If full capacity pop the tail and delete it. Otherwise just move to head and return the value of it.

Design Browser History You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps. Implement the BrowserHistory class: BrowserHistory(string homepage) Initializes the object with the homepage of the browser. void visit(string url) Visits url from the current page. It clears up all the forward history. string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps. string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.

Doubly linked list. Visiting a url, set the current node next and that new node prev. Than update the current node. Both forward and back is while self.current.next and steps keep going back.

Most Profit Assigning Work You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: - difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]). - Every worker can be assigned at most one job, but one job can be completed multiple times. For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0. Return the maximum profit we can achieve after assigning the workers to the jobs.

Easy, sort list zip profits and difficulty, loop through workers add up the highest profit then break out of loop for the next worker.

Longest Increasing Path in a Matrix Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).

First is a clean dfs solution. ans = 1 then check all 4 directions and boundaries and then ans = max(ans, 1 + dfs()) Next is topological sorting, we create the indegrees and the ones with 0 get added to a queue. We then check level by level increasing ans by 1. We check 4 directions, if its greater than reduce that indegrees than if 0 add to queue. Return ans after.

Buddy Strings Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad".

First we check the length, if they don't match its False. Then we check if they are the same word, if they are check that that there is at least one extra char dupe. If there isn't return False if there is we can return True Next, we go through and find the differences, count and append them to track. If len > 2 return false. We need exactly 2 diffs. Then we check to see that differences match up with the corresponding index for each one. s[diff[0]] == t[diff[1]].

Sliding Window Maximum You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

For this problem, the brute force solution is to slice a window each time and get the max element. We can do better though. We can use a queue. Basically for each index. Before we add it to the queue, we pop all elements that are outside the window first from the left. Then from the right we keep popping if its smaller than the current element. Then we append the current element index. If our current index is >= k then we append the front of the queue to the result. Might be easier to use tuples.

Next Greater Element III Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1. Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1. Example 1: Input: n = 12 Output: 21

I like my solution better of generating all possible combinations of the ints and then sorting and looking through to find the one just greater. The official solution though is tricky. You need to scan from right to left and look for the first decreasing element. If < 0 return -1, but we find it and then find the first element right to left thats greater than it. Once we do, we swap. After swapping we return everything to the left of i reversed. 1 5 8 4 7 6 5 3 1 1 5 8 [4] 7 6 [5] 3 1 1 5 8 5 / 7 6 4 3 1 1 5 8 5 / 1 3 4 6 7

Car Pooling There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.

I used a min heap where I sort by the start time and then create a min heap by its end time. I go through each trip and then if the start time is after the top of the min heaps end time, i keep popping and decreasing current capacity. If not, I just push into to min-heap and update the capacity. If the capacity is over return False. Another more intuitive approach is just go through each trip once and at the start +passengers and at the end -passengers into an array. Sort that array of timestamps and just iterate through calculating the capacity.

Making A Large Island You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s.

If you see a 1, uniquely identify the island and calculate its size. Then another around the grid looking for 0's. Calculate 1 + the islands around it. Return max. ans starts as 0 if no areas else areas.values

Maximum Profit in Job Scheduling: We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time X you will be able to start another job that starts at time X. Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70] Output: 120 Explanation: The subset chosen is the first and fourth job. Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.

Let's first format the data with start, end, and profit. We are then able to do this recursively with memoization. Starting at the beginning, we sort by the start times. At this state, we can either take the first jobs profit and then check the next possible job which is after this jobs end time or we skip the current and move on to the next job. Know that where we look next the start time are sorted so we will also check the next available job. We can also use binary search to find that next job. We then want to take the profit of what was bigger skipping or taking. O(NlogN) Time

Serialize and Deserialize Binary Tree

Preorder traversal to encode recursive. For decoding, preorder traversal too. popping at none or first.

1143. Longest Common Subsequence Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". A common subsequence of two strings is a subsequence that is common to both strings.

Recursive, if at end return 0. if both match increment both pointers. otherwise get the max of either incrementing the left or right pointer and cache the function.

Sudoku Solver Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must occur exactly once in each column. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. The '.' character indicates empty cells.

This is a backtracking problem. We use sets to keep track of every row, every col and also the sub boxes i // 3 * 3 + j // 3. Then we gotta loop through and for the values that have one, keep track of the empty spots and update the trackers for the rows/cols/boxes. Then our dfs function will go through each spot in spots (candidates). Our base case is if we reached the end. We go through 1-10, for each of these candidates (checking within bounds) then add to visited., update the board, cell + 1 then backtrack from that value.

84. Largest Rectangle in Histogram Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

This is a hard problem. The idea is to maintain a monotonic stack. We chain 0's in beginning and end to make this easier for calculating. But basically we keep a stack of heights and index as long as its increasing. But if the height is decreasing, we start calculating areas and heights and popping. Thats the general idea. The hard part is the indices imagination.

Count Subarrays With Fixed Bounds You are given an integer array nums and two integers minK and maxK. A fixed-bound subarray of nums is a subarray that satisfies the following conditions: The minimum value in the subarray is equal to minK. The maximum value in the subarray is equal to maxK. Return the number of fixed-bound subarrays. A subarray is a contiguous part of an array.

This is a weird thinking problem but the idea is this. iterate through, looking and update the indices of an out of bounds number, the minK idx and the maxK idx. If we have a value for both what we are going to do is this. The number of subarrays = either the max of 0 or min(minK_idx,maxk_idx) - bad_pos. Visuality it in your head.

Search Suggestion System You are given an array of strings products and a string searchWord. Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return a list of lists of the suggested products after each character of searchWord is typed.

This is another prefix trie. We sort our input lexicographically. For each word we add a node to the tree. Each node has children, a list of words and a count. Basically for each letter in the word as we go through, we add the word if it is under 3. For searching we then for each letter traverse the tree and return the num words. We use a self.node tracker in the trie to keep track of where we are at.

K-Similar Strings Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2. Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.

This is pretty hard. But think of it this way, theres a start node, then a good swap is an edge between that node and the next. We do a BFS to do this, level by level. The hard part here is understanding what is a good swap. A good swap is first where A[i] != B[i], then we check if A[i] == B[j] then we check that B[j] != S[j] boom then that there means (think down right up maybe) we should check that node and add it. A[i] == B[j] != A[j].

Similar String Groups Two strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X. For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts". Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?

This one is a bit tricky. So, we go through each string, store a variable of group found -1, if nothing in current groups just append it. Otherwise, go through each group, then each string in the group, check if its similar. If it is and we have not found a match before just append it to the group. If we already found a previous matching group we want to merge the two together. Then delete one of them.

Shortest Path to Get Food You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell. You are given an m x n character matrix, grid, of these different types of cells: '*' is your location. There is exactly one '*' cell. '#' is a food cell. There may be multiple food cells. 'O' is free space, and you can travel through these cells. 'X' is an obstacle, and you cannot travel through these cells. You can travel to any adjacent cell north, east, south, or west of your current location if there is not an obstacle. Return the length of the shortest path for you to reach any food cell. If there is no path for you to reach food, return -1.

This one was straightforward. Just BFS. I messed up on one of the conditionals need to check to make sure != 'X' is the one there for adding to the queue.

Maximum Path Quality of a Graph There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime. A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum). Return the maximum quality of a valid path. Note: There are at most four edges connected to each node.

This problem def sucks, its a dfs backtracking problem but struggled hard on this. The time left and total and visited set is what makes it hard. Just know you should pass in total, visited and calculate time left. The visited stuff man.

Shortest Distance from All Buildings You are given an m x n grid grid of values 0, 1, or 2, where: 1. each 0 marks an empty land that you can pass by freely, 2. each 1 marks a building that you cannot pass through, and 3. each 2 marks an obstacle that you cannot pass through. You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right. Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1. The total travel distance is the sum of the distances between the houses of the friends and the meeting point. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

This problem has a few parts that make it tricky but the overall steps are to find all the buildings store in an array, find all the empty lands / candidates. Then go through each building, do a bfs level by level and updating the distance of the candidate_lands. The caveat here is that we do set difference on the candidate lands and what was visited to figure out what lands to delete (couldn't reach). After that we just get the min of the candidate lands value and return that else return -1 if there are no candidate_lands or buildings.

Basic Calculator II Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

This solution was the most straightforward one. We basically sum the stack at the end. We have a stack, operator and number. For each character if its a digit we update the number. If the its an operator or the last character we use that prev operator we stored. If its plus or minus just append positive or negative that number. If its multiplication or division, we pop out then throw in the right answer back in. Then we reset the current number and update the operator to the current one.

Minimum Degree of a Connected Trio in a Graph You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.

To do this, create the graph first. Store edges as a set. We then go through each node i, then go through each node j to see if they are neighbors (skip if not) then go through each node k to see if its neighbors with i, j and k. If it is sum the edges up - 6 to get the indegrees than update min count.

Next Permutation A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). For example, the next permutation of arr = [1,2,3] is [1,3,2]. Similarly, the next permutation of arr = [2,3,1] is [3,1,2]. While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement. Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.

To do this, first we get a pointer to the second to last number. We want to get he index of the first decreasing element. Then with that index, if its greater than 0 (if not then reverse entire thing), new pointer at end and we want to find the first number thats greater. Once we find that, swap the two. Then reverse everything to the right of i + 1. This is because we found all the elements in increasing order earlier right so to get just the next greater number we need to reverse them.

Serialize and Deserialize N-ary Tree Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize an N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that an N-ary tree can be serialized to a string and this string can be deserialized to the original tree structure. For example, you may serialize the following 3-ary tree

To serialize, we do a level order traversal but different. We add to the encoding the node value and the len count of its children. Like 2:3,5:4 etc. Deserialization is tricky here, we first create the root node and starting queue and initialize idx to 1. Updating the current nodes children and then appending to queue the child and incrementing index each time. Then we return the root.

Basic Calculator Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Use a stack, and keep track of the operand, result and sign. If its a number just keep multiplying by ten and adding rightmost digit. if its plus or minus we update the result by adding the sign times the current operand then change the sign for minus to -1. For both, we update the operand to 0 afterwards. For open parenthesis we want to throw in the current result and sign onto the stack to keep track and reset the result and sign. For closed parenthesis, we sum up the current res and sign, then multiple by the prev sign and add prev result. At the end for last item on stack we take the res and multiply by sign and operand.

Find K Closest Elements Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| < |b - x|, or |a - x| == |b - x| and a < b Example 1: Input: arr = [1,2,3,4,5], k = 4, x = 3 Output: [1,2,3,4] Example 2: Input: arr = [1,2,3,4,5], k = 4, x = -1 Output: [1,2,3,4]

We use bisect left binary search to find the closest element to X. Basically where it would place X. Then minus 1 to get the index. Thats going to be our left and right is +1 that. Now, while the window is less than k. If left is -1 we expand right, if right is at the edge we expand left. Depending on whether left or right is closer to X we expand that way. Then we return that window.

Similar String Groups Two strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X. For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts". Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?

create a groups list. go through each string, found-group = -1, than go through every string in each group list. if two strings are similar (diff_count <= 2) than if found-group = -1, add it into that otherwise if there was a previously found one, merge them together and then delete one of them. Return the len of group list

Possible Bipartition We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group. Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.

graph the dislikes undirected. BFS on each node. source is -1, mark neighbors opposite, 1. keep array to keep track. If at any point same color while bfs'ing alternating return False otherwise true


संबंधित स्टडी सेट्स

PrepU ch.27 safety, security, and emergency preparedness

View Set

chapter 3- chirality and stereoisomers

View Set

FINC 409 - Chapter 11 Practice Problems

View Set

Chapter 22: Complications Occurring During Labor and Delivery

View Set