leetcode Flashcards
- Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Input: nums = [1,3,5,6], target = 5
Output: 2
int searchInsert(vector& nums, int target) { int l = 0; int h = nums.size()-1;
while (l<=h){ int mid = l + (h-l)/2;
if (target == nums[mid]){ return mid; } else if (target < nums[mid]){ h = mid-1; } else{ l = mid+1; } }
return l; }
278. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. Input: n = 5, bad = 4 Output: 4 Explanation: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version.
int firstBadVersion(int n) { int l= 1; int h = n; int result = n;
while (l<=h){ int mid = l+(h-l)/2;
if (isBadVersion(mid)){ result = mid; h = mid-1; } else{ l = mid+1; } }
return result; }
- Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
int search(vector& nums, int target) { int l = 0; int r = nums.size()-1;
while(l<=r){ int mid = l+(r-l)/2; if (nums[mid] == target){ return mid; } else if (nums[mid] > target){ r = mid-1; } else { l = mid+1; } }
return -1; }
- You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:
numberOfBoxesi is the number of boxes of type i.
numberOfUnitsPerBoxi is the number of units in each box of the type i.
You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.
Return the maximum total number of units that can be put on the truck.
Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
Output: 91
int maximumUnits(vector>& boxTypes, int truckSize) { priority_queue> pq;
for(int i=0; i
- Tic-tac-toe is played by two players A and B on a 3 x 3 grid. Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return “Draw”. If there are still movements to play return “Pending”.
Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: “A”
string tictactoe(vector>& moves) { int n=3;
if (moves.size() < 5){ return "Pending"; }
vector x (n,0); vector y (n,0); vector diag (2,0);
int player = 1; for(int i=0; i
937.You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.
There are two types of logs:
Letter-logs: All words (except the identifier) consist of lowercase English letters.
Digit-logs: All words (except the identifier) consist of digits.
Reorder these logs so that:
The letter-logs come before all digit-logs.
The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
The digit-logs maintain their relative ordering.
Return the final order of the logs.
Input: logs = [“dig1 8 1 5 1”,”let1 art can”,”dig2 3 6”,”let2 own kit dig”,”let3 art zero”]
Output: [“let1 art can”,”let3 art zero”,”let2 own kit dig”,”dig1 8 1 5 1”,”dig2 3 6”]
vector reorderLogFiles(vector& logs) { map> sortedLetterLogs; vector digitLogs;
vector r; for(auto val : logs){ int index = val.find(' '); if(isdigit(val[index+1])){ digitLogs.push_back(val); } else{ sortedLetterLogs[val.substr(index+1,val.length()-1)].insert(val); } }
for(auto m : sortedLetterLogs){ for(auto l : m.second){ r.push_back(l); } }
for (auto v : digitLogs){ r.push_back(v); } return r; }
- Write a function that reverses a string in-place. The input string is given as an array of characters s.
Input: s = [“h”,”e”,”l”,”l”,”o”]
Output: [“o”,”l”,”l”,”e”,”h”]
void reverseString(vector& s) { int l=0; int h=s.size()-1;
while(l
- Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Input: s = “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
string reverseWords(string s) {
for(int i=0, j=0 ; i<=s.size(); i++){ if(s[i]==' ' || i == s.size()){ swap(s,j,i-1); j=i+1; } } return s; }
void swap(string& s, int l, int h){ while(l
- Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
vector twoSum(vector& numbers, int target) { int l=0; int h=numbers.size()-1;
while(lval){ l++; } else{ h--; } }
return vector{l+1,h+1}; }
- Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
void moveZeroes(vector& nums) { int l = 0;
for(int r=0; r& nums, int l, int r){ int inter = nums[l]; nums[l] = nums[r]; nums[r] = inter; }
- Given an array, rotate the array to the right by k steps, where k is non-negative.
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
void rotate(vector& nums, int k) { if (k==0 || k%nums.size()==0) return; swap(nums, 0, nums.size()-1); k = k%nums.size(); swap(nums, 0, k-1); swap(nums, k, nums.size()-1); }
void swap(vector& nums, int l, int h){ while(l
- Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
vector sortedSquares(vector& nums) { vector res(nums.size(), 0); int l = 0; int h = nums.size()-1; int i = h;
while(l<=h){ res[i--] = abs(nums[l]) < abs(nums[h]) ? nums[h]*nums[h--] : nums[l]*nums[l++]; } return res; }
- An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with newColor.
Return the modified image after performing the flood fill.
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
vector> floodFill(vector>& image, int sr, int sc, int newColor) {
if (image[sr][sc] == newColor)
return image;
dpsFill(image, sr, sc, image[sr][sc], newColor); return image; }
void dpsFill(vector>& image, int sr, int sc, int sColor, int newColor){ if(sr<0 || sc<0 || sr>=image.size() || sc>=image[0].size() || image[sr][sc] != sColor) return;
image[sr][sc] = newColor; dpsFill(image, sr-1, sc, sColor, newColor); dpsFill(image, sr+1, sc, sColor, newColor); dpsFill(image, sr, sc-1, sColor, newColor); dpsFill(image, sr, sc+1, sColor, newColor); }
- 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.
Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.
int maxAreaOfIsland(vector>& grid) { set> seen; int max_area = 0;
for (int i=0; i>& grid, int r, int c, set>& seen){ if (r < 0 || r>= grid.size() || c <0 || c>=grid[0].size() || seen.find({r,c}) != seen.end() || grid[r][c] == 0) return 0; seen.insert({r,c}); return (1 + areaCal(grid, r-1, c, seen) + areaCal(grid, r+1, c, seen) + areaCal(grid, r, c-1, seen) + areaCal(grid, r, c+1, seen)); }
Convert 1D to 2D array given m rows and ncols.
Input: [1,2,3,4], m=2, n=2
output: [[1,2], [3,4]]
vector> multidimension (vector A, int m, int n){ if (m*n != A.size()) return null; vector> res(m, vector(n)); for(int i=0; i