LeetCode

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

39. Combination Sum Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

Backtracking to build combinations

35. Search Insert Position 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.

Binary search

42. Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Calculate right maximum for each index, track left maximum while iterating through array and calculating water trapped using the maximums

136. Single Number Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

HashSet

28. Implement strStr() Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Input: haystack = "hello", needle = "ll" Output: 2

Iterate through haystack, checking substring

54. Spiral Matrix Given an m x n matrix, return all elements of the matrix in spiral order.

Pointers/limits to check moving in each direction

203. Remove Linked List Elements Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Start with removing the head if needed. Predecessor pointer, iterate and remove the target.

141. Linked List Cycle Given head, the head of a linked list, determine if the linked list has a cycle in it. Return true if there is a cycle in the linked list. Otherwise, return false.

Tortoise and hare pointers

7. 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.

Use long to store result, pop and add digit by digit using % and /. Use abs and check if long > MAX_VALUE

12. Integer to Roman Given an integer, convert it to a roman numeral.

While loop for each numeral, largest to smallest. Cut down the number accordingly

190. Reverse Bits Reverse bits of a given 32 bits unsigned integer.

if (i < 32) result = result << 1 // make room result += n & 1 // add the next bit n = n >> 1 // next input

148. Sort List Given the head of a linked list, return the list after sorting it in ascending order.

Build TreeMap<Integer, ArrayList<Nodes>>. Iterate through TreeMap and build the sorted list

139. Word Break Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation.

Build boolean [] backwards, check the current substring against the dictionary and check the corresponding index in memory, if it fits set that index in memory to true. Return memory [0]

5. Longest Palindromic Substring Given a string s, return the longest palindromic substring in s. Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer.

Check each index as the center of a palindrome by spreading left/right

21. Merge Two Sorted Lists You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.

Comparison merge between current nodes

112. Path Sum Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

DFS while tracking current total

169. Majority Element Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

HashMap<Integer, Count> or sorting

97. Interleaving String Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: s = s1 + s2 + ... + sn t = t1 + t2 + ... + tm |n - m| <= 1 The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...

HashMap<Integer, Integer> to store all possible indices for each string. Update to a new HashMap for each character by iterating through previous indices and seeing if they are still valid after checking the next character

49. Group Anagrams Given an array of strings strs, group the anagrams together. You can return the answer in any order.

HashMap<String, List> using a sorted string as the key

122. Best Time to Buy and Sell Stock II You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.

If previous < next, profit += the difference

53. 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.

If the current total goes negative, reset the total. Otherwise keep adding numbers while tracking the maximum

57. Insert Interval You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]

Iterate through the start sorted intervals, if it overlaps with the target, merge.

48. Rotate Image You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

Iterate through the top left quarter of the matrix, swapping the 4 corresponding cells

2. 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.

Manual addition of the node values while tracking carryover

22. Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Recursively add any valid functions until reaching the right number of opening/closing parentheses

78. Subsets Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.

Recursively either choose to include/skip value, incrementing index either way. Add to the result once index == numbers.length

118. Pascal's Triangle Given an integer numRows, return the first numRows of Pascal's triangle.

Seed the first row. For each previous row, combine 2 adjacent values to sum to the next row. Manually add 1 to the start and end of each row

19. 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.

Separate pointers by n, traverse to the end

128. Longest Consecutive Sequence Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

Sorting, else use HashSet and try to start sequences if the previous value is missing

91. Decode Ways A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: "AAJF" with the grouping (1 1 10 6) "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". Given a string s containing only digits, return the number of ways to decode it.

int [] to store decodings at each index, iterate string backwards seeing if can read one character (0-9) or if can read two characters (10-26), array[i] = [i+1] and/or [i+2] if can read 1/2 characters. Return array[0]

45. Jump Game II Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index. Input: nums = [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.

int [] to track number of jumps to each index, iterate through array and update all jump locations

73. Set Matrix Zeroes Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.

2x HashSet for tracking columns/rows with a 0, iterate through array and set everything to 0 if needed

3. Longest Substring Without Repeating Characters Given a string s, find the length of the longest substring without repeating characters. Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.

Array for character counts in window, sliding window while keeping counts below 1

116. Populating Next Right Pointers in Each Node 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.

BFS to build each level, assign pointers while popping from the queue

117. Populating Next Right Pointers in Each Node II Given a binary tree 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

BFS to build each level, assign pointers while popping from the queue

102. 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).

BFS while using a queue to track each level

103. Binary Tree Zigzag Level Order Traversal Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

BFS while using a queue to track each level, reversing every other using a flag

107. Binary Tree Level Order Traversal II Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).

BFS with a queue to save nodes in each level. Collections.reverse(result)

200. Number of Islands Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return 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.

BFS with a visited [][], increment island count after each queue is cleared

111. Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

BFS, check if each node is a leaf

199. Binary Tree Right Side View Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

BFS, once the level queue is empty, add the last node value to the result

40. Combination Sum II Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination.

Backtracking to build combinations, check that !result.contains(combination) After adding number, skip all duplicates

162. Find Peak Element A peak element is an element that is strictly greater than its neighbors. Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. You must write an algorithm that runs in O(log n) time.

Binary search based on the slope

74. Search a 2D Matrix Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: - Integers in each row are sorted from left to right. - The first integer of each row is greater than the last integer of the previous row.

Binary search row -> binary search column. Alternatively, pointer in the top right, if too small, increase row, if too large, decrease column

33. Search in Rotated Sorted Array There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

Binary search to find inflection point, binary search the correct partition if (array[mid] < array[0]) max = mid-1; else min = mid+1

81. Search in Rotated Sorted Array II There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.

Binary search to find inflection point, binary search the correct partition if (array[mid] < array[0]) max = mid-1; else min = mid+1 While searching, slide the left and right pointers towards the middle if they match their neighbors

153. Find Minimum in Rotated Sorted Array Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times. [0,1,2,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. Given the sorted rotated array nums of unique elements, return the minimum element of this array. You must write an algorithm that runs in O(log n) time

Binary search to find the inflection point if (array[mid] < array[0]) max = mid-1; else min = mid+1

143. Reorder List You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → ... → Ln - 1 → Ln Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → ... You may not modify the values in the list's nodes. Only nodes themselves may be changed.

Build HashMap<Node, Predecessor> while moving fast pointer to the end. Iterate towards the middle while inserting the fast node in between the slow nodes. Traverse backwards using the HashMap

46. Permutations Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Build permutations with backtracking, for loop for all possible numbers, skipping numbers already in the set

61. Rotate List Given the head of a linked list, rotate the list to the right by k places. Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3]

Count nodes, rotation = k % nodes. Find target node and move pointers.

114. Flatten Binary Tree to Linked List Given the root of a binary tree, flatten the tree into a "linked list": The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The "linked list" should be in the same order as a pre-order traversal of the binary tree.

DFS preorder traversal to add nodes to a queue, pop nodes from the queue and build the LinkedList

104. 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

DFS to find maximum depth

79. Word Search Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

DFS using recursive backtracking and a history array. Start from each index.

113. Path Sum II Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

DFS while tracking current total and path. Add path if the total == target

110. Balanced Binary Tree Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

DFS, when reaching a leaf, check the height

198. 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.

DP tracking previous and previousPrevious. Current = max(previous, previousPrevious + value[i])

70. 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?

DP tracking the two previous steps, current = previous + previousPrevious

92. Reverse Linked List II Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

Find section to reverse, reverse until hitting right pointer. Reattach different sections

15. 3Sum Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

For loop containing 2Sum

16. 3Sum Closest Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers.

For loop containing 2Sum

133. Clone Graph Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; }

HashMap<Integer , Node> for holding new nodes. BFS to visit all nodes to create new nodes. BFS again to assign neighbors.

138. Copy List with Random Pointer A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y. Return the head of the copied linked list.

HashMap<OldNode, NewNode>, iterate through to create the nodes, iterate again to assign neighbors

55. Jump Game You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise.

Iterate in reverse, greedily update the target if we can reach it. Works because there is no minimum jump distance

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

Iterate through and flip pointers

152. Maximum Product Subarray Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array.

Iterate through array tracking the maximum +product and the -product. Reset if current = 0

8. 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). The algorithm for myAtoi(string s) is as follows: Read in and ignore any leading whitespace. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2). If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1. Return the integer as the final result.

Iterate through string, follow steps

24. Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Iterate through the list and swap nodes

134. Gas Station There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique

Iterate through the route, reset the possible starting point if we run out of gas. Attempt the trip from the discovered start.

125. Valid Palindrome A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.

Left and right pointers, skip necessary characters and increment towards the center

146. 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.

Map<Key, Value> keyValue ArrayDeque<Key> queue Map<Key, SkipCounter> ignore When accessing elements, add to the back of the queue and increment SkipCounter for the previous value in the line. When trimming keyValue to capacity, skip values as appropriate

4. Median of Two Sorted Arrays Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

Merge arrays, return median

155. 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(int 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.

Nodes containing the current minimum and value

23. Merge k Sorted Lists You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.

Queue of lists, comparison merge the first two lists and add the result to the back of the queue

98. 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.

Recursive DFS with long maximum recursive(left) check value against maximum recursive(right) return left && right

131. Palindrome Partitioning Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

Recursive backtracking using a start and finish index. Add a palindrome if valid, else skip and increment the finish index

100. Same Tree Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Recursive call on children after checking the existence of children

17. Letter Combinations of a Phone Number Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

Recursively add all possible letters for each digit

108. 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.

Recursively find the middle of the array and create a new node. Repeat for the children, dividing the array appropriately

189. Rotate Array 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]

Reverse left of inflection, reverse right of inflection, reverse the entire array

76. Minimum Window Substring Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.

Sliding window using HashMap to the needed characters in the current window. If all character counts are <= 0, update the substring

83. Remove Duplicates from Sorted List Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Slow and fast pointers, if fast.val == slow.val, remove fast

75. Sort Colors Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

Slow pointer for tracking the sorted array, faster pointer for searching the array. If fast = target element, swap with slow. Repeat for all targets

90. Subsets II Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.

Sort input. Recursively either choose to include/skip value, incrementing index either way. Add to the result once index == numbers.length

56. Merge Intervals Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Sort intervals by start, iterate through and merge while the current interval overlaps

20. Valid Parentheses Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

Stack

150. Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

Stack for numbers, switch for operators When checking numbers, check last character because of negative numbers

167. Two Sum II - Input Array Is Sorted 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. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space.

Start and end pointer, if sum > target, decrement end, otherwise increment start

67. Add Binary Given two binary strings a and b, return their sum as a binary string.

StringBuilder add on each digit sum while tracking the carry

6. Zigzag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows

StringBuilder for each row, iterate through string and add the character onto the corresponding row. Combine the rows

142. Linked List Cycle II Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

Tortoise and hare pointers. After they converge, start iterating from the head and iterating the tortoise. When they converge, that is the start of the cycle

47. Permutations II Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

Track included numbers with HashSet. Build permutations with backtracking, for loop for all possible numbers, skipping number indices already in the set

121. 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.

Track minimum, track max (current - minimum)

11. Container With Most Water You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store.

Two pointers at min and max, move the shorter pointer to the next higher line. Compare with maximum

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.

Two pointers at min and max, shift the pointer towards the answer

18. 4Sum Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: - 0 <= a, b, c, d < n - a, b, c, and d are distinct. - nums[a] + nums[b] + nums[c] + nums[d] == target

Wrap for loop with 2Sum at the center

64. Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time.

int [][] is store current sum to each location, calculate each cell with min(upper + value, left + value). Return the bottom right cell value

63. Unique Paths II You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner.

int [][] is store paths to each location, seed the top row and the leftmost column with 1 unless there is an obstacle blocking. Iterate through the array, top to bottom, L to R, each cell = top cell + left cell. Skip obstacles.

62. Unique Paths There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

int [][] is store paths to each location, seed the top row and the leftmost column with 1. Iterate through the array, top to bottom, L to R, each cell = top cell + left cell

105. Construct Binary Tree from Preorder and Inorder Traversal Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

preorder[0] = current root. Partition inorder[start, finish] based on the current root. Recursively repeat.

191. 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).

while (n != 0) count += n & 1 n = n >>> 1


Kaugnay na mga set ng pag-aaral

College and careers final review-Bellinger

View Set

Module 2Demand in any period that is outside the limits established by management policy. This demand may come from a new customer or from existing customers whose own demand is increasing or decreasing.

View Set

Chapter 5 - Statistical Inference

View Set

Electrical Theory 5th 1st Final Exam

View Set

Explain the similarities and differences in climatic characteristics between Tropical Monsoon (Am) and Tropical Desert (BWh) climates. (9m)

View Set

Symbiotic Relationships-Practice

View Set

AP Gov: Unit 2: Public Opinion and Polling

View Set