LeetCode Review

¡Supera tus tareas y exámenes ahora con Quizwiz!

Find Peak Element Solution A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that nums[-1] = nums[n] = -∞. Example 1: Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums = [1,2,1,3,5,6,4] Output: 1 or 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. Note: Your solution should be in logarithmic complexity.

Actually, there are 4 possibilities of the location of mid: 1. Peak: mid-1 < mid > mid+1 2. climbing: mid-1 < mid 3. declining: mid-1 > mid 4. Valley: mid-1 > mid < mid+1 Note that the last two scenarios are contained in the last "else" condition.

Remove Nth Node From End of List Solution Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Follow up: Could you do this in one pass?

If there is only one node; if n equal to the total length.

Rotate Array Solution Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and 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]

Note the how the sections are sliced.

Inorder Successor in BST Solution Given a binary search tree and a node in it, find the in-order successor of that node in the BST. The successor of a node p is the node with the smallest key greater than p.val.

Same, do not think too much.

Symmetric Tree Solution Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3

The recursive solution is based on the right and left children

Kth Smallest Element in a BST Solution Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note:You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Example 1: Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1 Example 2: Input: root = [5,3,6,2,4,null,null,1], k = 3 5 / \ 3 6 / \ 2 4 / 1 Output: 3 Follow up:What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

Do not consider it too complicated. Since the inorder traversal is the process of building a ascending list from the BST, we just return current node val if k hit 0 while we are doing inorder traversal.

Implement strStr() Solution Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1

Note edge cases and the range of the loop

Container With Most Water Solution Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not slant the container and n is at least 2. The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. Example: Input: [1,8,6,2,5,4,8,3,7] Output: 49

Starting at the two ends of the list, since the volume is bounded by the shorter end of the two, consider the case if left is shorter than right, then the volume is bounded by left, if we move right height, the volume is going to shrink, since the distance is shorter, so we can only move left in order to find any bigger volume.

Count and Say The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11.11 is read off as "two 1s" or 21.21 is read off as "one 2, then one 1" or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit. Note: Each term of the sequence of integers will be represented as a string.

1. Base case should contain n = 2 2. Loop starts from 1 so dont add if i > 1 into the condition for the first item. 3. Add the last pair outside the loop.

Merge Intervals Solution Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

1. Dont forget to sort the intervals first 2. Dont forget to attach the last prev outside of the loop

Meeting Rooms II Solution Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. Example 1: Input: [[0, 30],[5, 10],[15, 20]] Output: 2 Example 2: Input: [[7,10],[2,4]] Output: 1

1. Dont forget to sort the starts and ends at the beginning 2. The first condition is to check if the current starting time is earlier (strict less than) the ending time. Consider the first situation where s and e both equal to 0, then start[s] is strictly less than ends[e] and we need 1 room for this.

3Sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]

Note that this is different from Binary Search hence the mid is not needed. Dont forget to sort the list as well.

Insert Delete GetRandom O(1) Solution Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Note that we need to change the index for the swapped element in the dictionary as well.

Generate Parentheses Solution Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ "((()))", "(()())", "(())()", "()(())", "()()()" ]

Note that we have to check the current values for l and r before we attach any new parenthesis to the current path. Otherwise the current path is going to blow up. Also the attach condition is when l==r==n, instead of either one of them equal to n, otherwise the attached path would miss the other half.

Number of Islands Solution Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: 11110 11010 11000 00000 Output: 1 Example 2: Input: 11000 11000 00100 00011 Output: 3

Fill only happens if the current value is 1. And it is independent from adding count in the main function.

Surrounded Regions Solution Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. Example: X X X X X O O X X X O X X O X X After running your function, the board should be: X X X X X X X X X X X X X O X X Explanation: Surrounded regions shouldn't be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

Find all the Os on the border then trace back.

Populating Next Right Pointers in Each Node Solution You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.

In the O(1) space case, the logic behind the two while loops is: 1. Identify if current node has left node, if yes, then do the two connections: a. left to right b. if current node has next, connect right to next.left 2. HORIZONTALLY move current node to node.next until it stops. This would connect the current horizontal level Then jump back to the anchor location and root = anchor.left VERTICALLY moves downwards.

Search a 2D Matrix II Solution Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example: Consider the following matrix: [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] Given target = 5, return true. Given target = 20, return false.

In the searching solution, the loop condition contains all the pixels in the matrix, once the loop ends, we just return False since no value found for all the pixels. If we exclude the bottom left corner from the loop, the edge cases are annoying.

Search in Rotated Sorted Array Solution Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1

Note that the condition for: the pivot point is at the latter half of the list, i.e. the list is ascending from left to mid point, is, nums[l] <= nums[mid] there is an equal sign there. Without it, the algorithm is not going to work.

Best Time to Buy and Sell Stock Solution Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. Example 1: Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price. Example 2: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.

Make the biggest difference

Intersection of Two Linked Lists Solution Write a program to find the node at which the intersection of two singly linked lists begins.

Note how the None situation is introduced into the while condition, i.e., None must be a element of the cycle, instead of skipped by the logic inside of the loop. Therefore, taking the next step and switch the links can not be done in one iteration.

Best Time to Buy and Sell Stock II Solution Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. 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 at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.

Note how the accumulated profit is calculated, if the next day's price is higher, we skip it.

Remove Duplicates from Sorted Array Solution Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example 1: Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length.

Note how the first item is skipped and how the comparison is done with the previous item

Reverse Linked List Solution Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

Note how the recursion is implemented

Valid Sudoku Solution Determine if a 9x9 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 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note in the box function, how the smaller board is accessed.

Valid Anagram Solution Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Note:You may assume the string contains only lowercase alphabets. Follow up:What if the inputs contain unicode characters? How would you adapt your solution to such case?

Note the case where len(s) != len(t)

Intersection of Two Arrays II Solution Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

Note the difference between sorted and unsorted

Search for a Range Solution Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] Example 2: Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]

Note the difference in including (l-=1, r+=1) and excluding (l+=1, r-=1) the values. When we are expanding the window, we compare the value OUTSIDE the current window with the current value so we DO NOT need to attach another line of increment after the while loop. If we are avoiding the duplicates, however, after the while loop, we need the current pointer to point to the NEW value, so we add another line of code after the while loop to jump on to the new value. The latter situation is related to ThreeSum Problem.

Two Sum Solution Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

Note the key value pair in the dictionary should be {number in the list: its index}

Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Above is a 7 x 3 grid. How many possible unique paths are there? Note: m and n will be at most 100. Example 1: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right

Note the size of the dp map.

Spiral Matrix Solution Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. Example 1: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5] Example 2: Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Note: 1. Dont forget to return res after all the recursive alls, otherwise nothing would be returned 2. The third case, leftwards, we need to append the row in reverse order.

Single Number Solution Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1

O(1) space, note that 0^x = x

Linked List Cycle Solution Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Since the break condition inside of the loop is fast == slow, when we initialize these two pointers, they need to be at different locations.

Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. Example 1: Input: "3+2*2" Output: 7 Example 2: Input: " 3/2 " Output: 1 Example 3: Input: " 3+5 / 2 " Output: 5 Note: You may assume that the given expression is always valid. Do not use the eval built-in library function.

There is a character delay mechanism embedded.

Word Search Solution Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false.

The dfs takes the word seqence but only searches the first char, if its empty, we reached the bottom, return True. If the current first char found in this location, we mask it with # since we cannot use the same char twice. Then we search the adjacent locations recursively. Note that we need to unmask the current location after all the recursive calls are done.

String to Integer (atoi) Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned.

Watch out for edge cases


Conjuntos de estudio relacionados

AI-900 MS Learn Practice Assessment

View Set

Chapter 4: Civil Liberties- Nationalizing the Bill of Rights

View Set

Lifetime Wellness Exam Study Guide

View Set

Spanish I. singular AR verb conjugation

View Set

Multiplication (8s, 9s and 10s) x6, x7, x8, x9, x10

View Set

EMT Chapter 34: Pediatric Emergencies

View Set

BUAD 3040 Finance Conceptual Problems Final

View Set