LeetCode Easy Backup

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

Single Number Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space.

If we take XOR of zero and some bit, it will return that bit. a XOR 0 = a If we take XOR of two same bits, it will return 0 a XOR a = 0 a⊕a=0 a XOR b XOR a = (a XOR a) XOR b = 0 XOR b = b a⊕b⊕a=(a⊕a)⊕b=0⊕b=b

Climbing Stairs You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

class Solution { public: ....int climbStairs(int n) { ........if (n < 2) ............return 1; ........ ........vector<int> nums(n+1); ........nums[0] = 1; ........nums[1] = 1; ........for (int i = 2; i <= n; i++) ............nums[i] = nums[i-1] + nums[i-2]; ........return nums[n]; ....} };

Hamming Distance The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them.

x XOR y to determine bits that are different between x and y. Then, count the 1's in x^y using bit manipulation. class Solution { public: ....int hammingDistance(int x, int y) { ........int count = 0; ........int z = x^y; ........while (z != NULL) { ............z &= z - 1; ............count++; ........} ........return count; ....} };

First Unique Character in a String Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Create hashmap counting each char in string. Then, iterate through string and if hash map count == 1, then return index. Else return -1.

Reverse String Write a function that reverses a string. The input string is given as an array of characters s.

Two pointers swap beginning and end of string

Count and Say The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = "1" countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string. To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying. Input: n = 1 Output: "1" Input: n = 4 Output: "1211" The following are the terms from n=1 to n=10 of the count-and-say sequence: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211

Establish base case. Then, create 2 string buffers. Iterate from 0 to n and, inside, iterate through each digit. Compare if current and previous digit are different. If so, then append to tmp buffer and reset count=0. If not, count++ and set prev digit. After exiting digit for loop, append the last digit to the tmp buffer. Set output buffer to tmp buffer.

Fizz Buzz Given an integer n, return a string array answer (1-indexed) where: answer[i] == "FizzBuzz" if i is divisible by 3 and 5. answer[i] == "Fizz" if i is divisible by 3. answer[i] == "Buzz" if i is divisible by 5. answer[i] == i if non of the above conditions are true. Input: n = 5 Output: ["1","2","Fizz","4","Buzz"]

Niave approach. Iterate through elements and append to array depending on i. For optimization, you can append "Buzz" to "Fizz" (str = "Fizz"; str += "Buzz";). This works well if there are multiple strings to append, such as FizzBuzzJazz.

Reverse Integer Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Pop and Push Digits & Check before Overflow

Valid Anagram Given two strings s and t, return true if t is an anagram of s, and false otherwise. Input: s = "anagram", t = "nagaram" Output: true

Sort both strings and return "s == t". Alternatively, store hash map of both strings. If hash map of s contains the same letters and same count of letters, they are equivalent.

Rotate array [reverse] 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] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]

k %= array.length rotate array from 0 to N-1 rotate array from 0 to k-1 rotate array from k to N-1

Two Sum Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

Add each number in the array to a hash map. Then, iterate through the array and calculate the complement (target - i). If the complement is in the hash map, then return a new vector with the complement and i.

Contains Duplicate Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Hash map

Depth First Traversals

(a) Inorder (Left, Root, Right) : 4 2 5 1 3 (b) Preorder (Root, Left, Right) : 1 2 4 5 3 (c) Postorder (Left, Right, Root) : 4 5 2 3 1 Breadth First or Level Order Traversal : 1 2 3 4 5

DFS Inorder Traversal

(a) Inorder (Left, Root, Right) : 4 2 5 1 3 Algorithm Inorder(tree) 1. Traverse the left subtree, i.e., call Inorder(left-subtree) 2. Visit the root. 3. Traverse the right subtree, i.e., call Inorder(right-subtree)

DFS Preorder Traversal

(b) Preorder (Root, Left, Right) : 1 2 4 5 3 Algorithm Preorder(tree) 1. Visit the root. 2. Traverse the left subtree, i.e., call Preorder(left-subtree) 3. Traverse the right subtree, i.e., call Preorder(right-subtree)

DFS Postorder Traversal

(c) Postorder (Left, Right, Root) : 4 5 2 3 1 Algorithm Postorder(tree) 1. Traverse the left subtree, i.e., call Postorder(left-subtree) 2. Traverse the right subtree, i.e., call Postorder(right-subtree) 3. Visit the root.

Tree Height / Max Depth

/* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(node* node) { ....if (node == NULL) ........return 0; ....else { ........int lheight = height(node->left); ........int rheight = height(node->right); ........return (lheight > rheight ? lheight : rheight) + 1; ....} }

Level Order Traversal / Breadth First Search Example: 1 2 3 4 5

/* Function to print level order traversal a tree*/ void printLevelOrder(node* root) { ....int h = height(root); ....int i; ....for (i = 1; i <= h; i++) ........printCurrentLevel(root, i); } /* Print nodes at a current level */ void printCurrentLevel(node* root, int level) { ....if (root == NULL) ........return; ....if (level == 1) ....cout << root->data << " "; ....else if (level > 1) { ........printCurrentLevel(root->left, level-1); ........printCurrentLevel(root->right, level-1); ....} }

Reverse Integer Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Pop numbers using x %= 10 and x /= 10. Check if rev < (INT_MAX-1)/10 OR rev < INT_MAX/10. Push numbers to reverse int using "rev = rev * 10 + pop".

String to Integer (atoi) Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

Check for overflow using "if (result > (INT_MAX - ((int)s[i] - '0'))/10)". Add to result using "result = result * 10 + ((int)s[i] - '0')"

Delete Node in a Linked List Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. It is guaranteed that the node to be deleted is not a tail node in the list. Input: head = [4,5,1,9], node = 5 Output: [4,1,9]

Delete node->next by copying the values in node->next into the current node. Then, delete node->next.

Palindrome Linked List Given the head of a singly linked list, return true if it is a palindrome. Input: head = [1,2,2,1] Output: true Input: head = [1,2] Output: false

Add all numbers to a vector. Then, iterate 1 ptr forward in the list and iterate 1 ptr backward through the list, comparing the front and back end values. Alternatively, find the list length, save ptr to the middle of the 2nd half of the list, and reverse the 2nd half of the list. Then, iterate through the first and second halves of the list, verifying each node's values match.

Min Stack Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: MinStack() initializes the stack object. void push(val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. int top() gets the top element of the stack. int getMin() retrieves the minimum element in the stack. Input ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] Output [null,null,null,null,-3,null,0,-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2

An invariant is something that is always true or consistent. You should always be on the lookout for useful invariants when problem-solving in math and computer science. Recall that with a Stack, we only ever add (push) and remove (pop) numbers from the top. Therefore, an important invariant of a Stack is that when a new number, which we'll call x, is placed on a Stack, the numbers below it will not change for as long as number x remains on the Stack. Numbers could come and go above x for the duration of x's presence, but never below. So, whenever number x is the top of the Stack, the minimum will always be the same, as it's simply the minimum out of x and all the numbers below it. Create a stack of pairs that stores the value and the minimum.

Merge Sorted Array You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]

Approach 2 already demonstrates the best possible time complexity, O(n+m), but still uses additional space. This is because the elements of array nums1 have to be stored somwhere so that they aren't overwritten. So, what if instead we start to overwrite nums1 from the end, where there is no information yet? The algorithm is similar to before, except this time we set p1 to point at index m - 1 of nums1, p2 to point at index n - 1 of nums2, and p to point at index m + n - 1 of nums1. This way, it is guaranteed that once we start overwriting the first m values in nums1, we will have already written each into its new position. In this way, we can eliminate the additional space. Interview Tip: This is a medium-level solution to an easy-level problem. Many of LeetCode's easy-level problems have more difficult solutions, and good candidates are expected to find them. Interview Tip: Whenever you're trying to solve an array problem in-place, always consider the possibility of iterating backwards instead of forwards through the array. It can completely change the problem, and make it a lot easier.

Best Time to Buy and Sell Stock [peak-valley approach] You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Calculate cumulative profit of peaks - valleys.

Reverse Bits Reverse bits of a given 32 bits unsigned integer. Input: n = 00000010100101000001111010011100 Output: 964176192 (00111001011110000010100101000000)

Bit by Bit Loop through each bit and build a new int with reverse bits using "result += bit << (31-i)". Divide and Conquer with Mask and Shift The idea can be considered as a strategy of divide and conquer, where we divide the original 32-bits into blocks with fewer bits via bit masking, then we reverse each block via bit shifting, and at the end we merge the result of each block to obtain the final result. class Solution { public: ....uint32_t reverseBits(uint32_t n) { ........n = (n >> 16) | (n << 16); ........n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8); ........n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4); ........n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2); ........n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1); ........return n; ....} };

Maximum Subarray Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.

Brute force. Calculate each subarray profit, storing maxProfit if profit > maxProfit. To use DP (and prevent recalculating previously calculated subarrays), add current nums[i] to previous subarray. Without DP, it's O(N^3). With DP, it's O(N^2). Kadane's algorithm. Iterate through each element and set "subarray = max(nums[i], subarray + nums[i]". Then, update maxSubarray as "max(maxSubarray, subarray)" (we don't set "maxArray = maxSubarray+subarray" because if we reset the sliding window, then we just consider subarray. O(N).

Best Time to Buy and Sell Stock You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Cache the min value in the price array. If current price i - min > profit, then profit = i - min. Return profit. This way, we skip elements not less than min. class Solution { public: ....int maxProfit(vector<int>& prices) { ........int profit = 0; ........int min = INT_MAX; ........for (int i : prices) { ............if (i < min) ................min = i; ............else if (i - min > profit) ................profit = i - min; ........} ........return profit; ....} };

Reverse Linked List Given the head of a singly linked list, reverse the list, and return the reversed list.

Create 1 ptr to iterate forward through the list, 1 ptr to store the previous node, and 1 ptr to store the next node. Then, loop forward through the list, setting node->next to the previous node.

Merge Two Sorted Lists Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4] Input: l1 = [], l2 = [0] Output: [0] Input: l1 = [], l2 = [] Output: []

Create a new ListNode prehead that contains a value less than l1 and l2, and a ptr to this prehead. Loop through l1 and l2, adding the lesser value to prehead. Return ptr.

Intersection of Two Arrays II Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]

Create hash map and insert all numbers in array. Then, iterate through the second array. If the number in the second array exists in the hash map AND the decremented value for that key is >= 0, then add it to the output vector.

Implement strStr() Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

Create hash<char, vector<int>> map of haystrack and store the indexes of the first letter in needle. Iterate through each vector<int> in map[needle[0]]. If index + needle.length > haystrack.length, return -1. If the substring of haystack starting at index matches needle, return index.

Symmetric Tree Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Create helper function that traverses the left and right subtrees. Verify that left subtree->left == right_subtree->right, and right_subtree->right == left_subtree->left, and check left->val == right->val for each traversal.

Power of Three Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x.

Iterative approach bool isPowerOfThree(int n) { ....if (!n) ........return false; ....while ((n % 3) == 0) ........n /= 3; ....return n == 1; } Math Approach Math approach does not work in all languages, like C++, due to precision errors. bool isPowerOfThree(int n) { ....double exp = log(n)/log(3); ....return exp == floor(exp); }

Plus One Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself. Input: digits = [1,2,3] Output: [1,2,4]

In a decrementing for loop, if the value == 9, then set the current number to 0. Else, increment by 1 and return the vector. If the for loop exits, that means the least significant digit == 9, so create a new vector with 1 as element 0 and append the current vector.

Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Input: strs = ["flower","flow","flight"] Output: "fl" Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.

Iterate through chars in first string and iterate through every other string, comparing the chars with the same index. If chars don't match, return the substring. Else, exit all loops and return the substring.

First Bad Version You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 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. You should minimize the number of calls to the API. Input: n = 5, bad = 4 Output: 4

Linear search by return the first iteration where isBadVersion(version)=true. Use binary search to narrow down the first iteration where isBadVersion(version)=true.

Number of 1 Bits Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Loop and Flip Loop through each bit, if "bit & 1" == 1, then weight++. Return weight. Bit manipulation trick Instead of checking every bit of the number, we repeatedly flip the least-significant 11-bit of the number to 00, and add 11 to the sum. As soon as the number becomes 00, we know that it does not have any more 11-bits, and we return the sum. The key idea here is to realize that for any number nn, doing a bit-wise AND of nn and n - 1n−1 flips the least-significant 11-bit in nn to 00. Why? Consider the binary representations of nn and n - 1n−1. 101101 (num=45) 101100 (num=44) 101100 (count=1) 101100 (num=44) 101011 (num=43) 101000 (count=2) 101000 (num=40) 100111 (num=39) 100000 (count=3) 100000 (num=32) 011111 (num=31) 000000 (count=4)

Maximum Depth of Binary Tree Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Input: root = [3,9,20,null,null,15,7] Output: 3

Recursion - If root == NULL, return 0. Else, recursively call left and right. Then, if left > right, return left + 1, else return right + 1.

House Robber You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.

Observe that the recurrence relation is "rob[0] = max(arr[0] + arr[2:N], arr[1:N])", or rob[i] = max(arr[i] + arr[(i+2):N], arr[(i+1):N])" Therefore, create variable house1 (arr[i-2]) and house2 (arr[i-1]). Iterate through the houses array, calculating "tmp = max(nums[i] + house1, house2)" and update house1 and house2.

Remove Nth Node From End of List Given the head of a linked list, remove the nth node from the end of the list and return its head. Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5] Input: head = [1], n = 1 Output: []

One pass using 2 ptrs. The first pointer advances the list by n+1n+1 steps from the beginning, while the second pointer starts from the beginning of the list. Now, both pointers are exactly separated by nn nodes apart. We maintain this constant gap by advancing both pointers together until the first pointer arrives past the last node. The second pointer will be pointing at the nnth node counting from the last. We relink the next pointer of the node referenced by the second pointer to point to the node's next next node.

Convert Sorted Array to Binary Search Tree Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5]

Preorder Traversal: Always Choose Left Middle Node as a Root. Implement helper function helper(left, right), which constructs BST from nums elements between indexes left and right: If left > right, then there is no elements available for that subtree. Return None. Pick left middle element: p = (left + right) // 2. Initiate the root: root = TreeNode(nums[p]). Compute recursively left and right subtrees: root.left = helper(left, p - 1), root.right = helper(p + 1, right).

Validate Binary Search Tree Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.

Preorder traversal while passing in low and high value for comparison. When visiting a node, if the current value is less than the low or higher than the high, return false; else return true. Alternatively, inorder traversal means for BST that each element should be smaller than the next one. Therefore, perform inorder traversal Left -> Node -> Right. When visiting the node, return false if root->val <= prev->val. class Solution { private: ....TreeNode* prev; public: ....bool inorder(TreeNode* root) { ........if (!root) ............return true; ........if (!inorder(root->left)) ............return false; ........if (prev && root->val <= prev->val) ............return false; ........prev = root; ........return inorder(root->right); ....} ....bool isValidBST(TreeNode* root) { ........return inorder(root); ....} };

Rotate array [brute force] 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] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]

Rotate the array k times, shifting each element right each time. k %= array.length to save time. k %= array.length() Iterate through k times { ....prev = last item ....iterate through array elements { ........tmp = array[i] ........array[i] = prev ........prev = tmp ....} }

Shuffle an Array Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. Implement the Solution class: Solution(int[] nums) Initializes the object with the integer array nums. int[] reset() Resets the array to its original configuration and returns it. int[] shuffle() Returns a random shuffling of the array. Input ["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []] Output [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

Shuffle array by swapping values. Technically, there's no requirement that you have to shuffle each value in the array, so we can get away with just 1 swap. Alternatively, you can create a bag of numbers that randomly selects numbers to insert into an output vector. Create an output vector, randomly selected indexes in the nums array, insert that index value into the output vector, and delete the randomly selected element from the nums array.

Count Primes Count the number of prime numbers less than a non-negative number, n. Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Sieve of Eratosthenes Create boolean array that stores which numbers are composite. All elements initialize to false by default. Then, iterate through from 2 to N (start at 2 since it's the first prime number. 0 and 1 are not prime), if nums[i] == TRUE, then loop through from 2 to N and update multiple of i to true. We loop while "i * i < N" because the smallest prime factor of a composite number n is less than or equal to root(n). So there is no point in checking further than the number as those get covered in the next numbers in the list and reduces complexity.

Missing Number Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8 Input: nums = [0,1] Output: 2

Sorting Sort the array. Then, iterate through 0 to nums.size() and if i != nums[i], then return i. O(log n). HashSet Create hash map of the nums array. Then, iterate from 0 to nums.size(), if hash map does not contain i, then return i. Math sum(i=0, n) i = n(n+1)/2. Calculate the expected and actual sum. expected - actual = missing number. Bit Manipulation Because we know that nums contains nn numbers and that it is missing exactly one number on the range [0..n-1][0..n−1], we know that nn definitely replaces the missing number in nums. Therefore, if we initialize an integer to nn and XOR it with every index and value, we will be left with the missing number. Consider the following example (the values have been sorted for intuitive convenience, but need not be): Index 0 1 2 3 Value 0 1 3 4 missing= =4∧(0∧0)∧(1∧1)∧(2∧3)∧(3∧4) =(4∧4)∧(0∧0)∧(1∧1)∧(3∧3)∧2 =0∧0∧0∧0∧2 =2 ​

Rotate Image You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]

Transpose and Reflect Array

Move Zeroes Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]

Two pointer technique. For design, create table with conditions [1,0], [0, 1], [0, 0], [1, 1]. 10 = i++, j++ 01 = swap, i++, j++ 00 = j++ 11 = i++, j++

Remove Duplicates from Sorted Array [2 ptrs]

Two pointers. If ptr 2 != ptr 1, then nums[ptr1] = nums[ptr2] and ptr1++. Return ptr2 + 1.

Valid Sudoku Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules.

Use 3 arrays of hash sets to store each int in every row, column, and 3x3 box. If any hash set already contains an integer, return false. Else, return true.

Linked List Cycle Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false. Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Use slow and fast ptr. Slow = slow->next. Fast = fast->next->next. Loop through all nodes while fast != slow, if fast or fast->next reaches NULL, then we reached the end of the list. If fast == slow, then hasCycle=true. Alternatively, use a hash set. Iterate through all nodes, if ListNode already exists in hash set, hasCycle=true; else, insert node into the hash set. Return false if all nodes added are unique.

Valid Parentheses Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Input: s = "()[]{}" Output: true Input: s = "{[]}" Output: true Input: s = "([)]" Output: false

Use stack to track the order in which parentheses should be opened or closed. class Solution { public: ....bool isValid(string s) { ........stack<char> st; ........for (char c : s) { ............switch(c) { ................case '(': ................case '{': ................case '[': ....................st.push(c); ....................break; ................case ')': ....................if (!st.size() || st.top() != '(') ........................return false; ....................else ........................st.pop(); ....................break; ................case '}': ....................if (!st.size() || st.top() != '{') ........................return false; ....................else ........................st.pop(); ....................break; ................case ']': ....................if (!st.size() || st.top() != '[') ........................return false; ....................else ........................st.pop(); ....................break; ............} ........} ........return st.size() == 0; ....} };

Binary Tree Level Order Traversal Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]]

class Solution { private: ....vector<vector<int>> result; public: ....int height(TreeNode* root) { ........if (!root) ............return 0; ........int left = height(root->left); ........int right = height(root->right); ........return max(left, right) + 1; ....} ....void levelOrderTraversal(TreeNode* root, int i, int level) { ........if (!root) ............return; ........if (i == 1) { ............result[level - 1].push_back(root->val); ........} else { ............levelOrderTraversal(root->left, i - 1, level); ............levelOrderTraversal(root->right, i - 1, level); ........} ....} ....void bfs(TreeNode* root) {........ ........for (int i = 1; i <= height(root); i++) { ............result.push_back(vector<int>()); ............levelOrderTraversal(root, i, i); ........} ....} ....vector<vector<int>> levelOrder(TreeNode* root) { ........bfs(root); ........return result; ....} };

Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807. Input: l1 = [0], l2 = [0] Output: [0] Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1]

class Solution { public: ....ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ........ListNode *n1 = l1, *n2 = l2; ........int carry = 0; ........int l1_len = 0, l2_len = 0; ........ ........while (n1 || n2) { ............if (n1) { ................l1_len++; ................n1 = n1->next; ............} ............if (n2) { ................l2_len++; ................n2 = n2->next; ............} ........} ........ ........if (l1_len >= l2_len) { ............n1 = l1; ............n2 = l2; ........} else { ............n1 = l2; ............n2 = l1; ........} ........ ........while (n1) { ............int total = n1->val + (n2 ? n2->val : 0) + carry; ............carry = total > 9; ............total %= 10; ............n1->val = total; ............ ............if (!n1->next && carry) { ................ListNode *node = new ListNode(1); ................n1->next = node; ................break; ............} ............ ............n1 = n1->next; ............n2 = n2 ? n2->next : n2; ........} ........ ........return l1_len >= l2_len ? l1 : l2; ....} };

Roman to Integer Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given a roman numeral, convert it to an integer.

class Solution { public: ....int helper(string s, int &i, char c1, char c2, int tens) { ........int result = 0; ........int j = i + 1; ........if (j < s.length()) ............if (s[j] == c1) { ................result += 4 * tens; ................i++; ............} else if (s[j] == c2) { ................result += 9 * tens; ................i++; ............} else { ................result += 1 * tens; ............} ........else ............result += 1 * tens; ........return result; ....} .... ....int romanToInt(string s) { ........int result = 0, j; ........for (int i = 0; i < s.length(); i++) { ............switch(s[i]) { ................case 'I': ....................result += helper(s, i, 'V', 'X', 1); ....................break; ................case 'V': ....................result += 5; ....................break; ................case 'X': ....................result += helper(s, i, 'L', 'C', 10); ....................break; ................case 'L': ....................result += 50; ....................break; ................case 'C': ....................result += helper(s, i, 'D', 'M', 100); ....................break; ................case 'D': ....................result += 500; ....................break; ................case 'M': ....................result += 1000; ....................break; ................default: ....................break; ............} ........} ........return result; ....} };

Pascal's Triangle Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

class Solution { public: ....vector<vector<int>> generate(int numRows) {........ ........vector<vector<int>> nums; ........nums.push_back(vector<int>{ 1 }); ........for (int i = 1; i < numRows; i++) { ............nums.push_back(vector<int>(i+1)); ............nums[i][0] = nums[i][i] = 1; ............for (int j = 1; j < i; j++) { ................nums[i][j] = nums[i-1][j-1] + nums[i-1][j]; ............} ........} ........return nums; ....} };


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

Conceptual Questions Finance 3320 Final

View Set

Cold War/ Decolonization Questions

View Set

Identifying web 2.0 technologies

View Set

Chapter 25 - Suicide and Nonsuicidal Self-Injury

View Set

AP GOVERNMENT CHAPTER 12: BUREAUCRACY

View Set

6c) Human Growth and Development chapter 6 questions

View Set