Leetcode Interview Problems

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/44

encourage image

There's no tags or description

Looks like no tags are added yet.

45 Terms

1
New cards

Two Sum

[Easy]

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

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

  • 2 <= nums.length <= 104

  • -109 <= nums[i] <= 109

  • -109 <= target <= 109

  • Only one valid answer exists.

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

Topics: Array, Hashmap

  • Use dictionary to keep track of visited numbers as you go

  • Check if complement of current already visited, then we found a pair


2
New cards

Valid Palindrome

[Easy]

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.

Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

Constraints:

  • 1 <= s.length <= 2 * 105

  • s consists only of printable ASCII characters.


Topics: String, Two Pointers

  • Two pointers going in to middle, skipping over non-alphanumerics by checking .isalnum()

  • If two lowercase letters don't match at any point, it's not a palindrome


3
New cards

Middle of the Linked List

[Easy]

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

Constraints:

  • The number of nodes in the list is in the range [1, 100].

  • 1 <= Node.val <= 100


Topics: Two Pointers, Linked List

  • Slow pointer, with a fast pointer moving 2x faster than slow

  • Checks while fast pointer is not None, and fast's next is also not None


4
New cards

Maximum Sum of Distinct Subarrays With Length K

[Medium]

You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:

  • The length of the subarray is k, and

  • All the elements of the subarray are distinct.

Return the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return 0.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [1,5,4,2,9,9,9], k = 3
Output: 15
Explanation: The subarrays of nums with length 3 are:
- [1,5,4] which meets the requirements and has a sum of 10.
- [5,4,2] which meets the requirements and has a sum of 11.
- [4,2,9] which meets the requirements and has a sum of 15.
- [2,9,9] which does not meet the requirements because the element 9 is repeated.
- [9,9,9] which does not meet the requirements because the element 9 is repeated.
We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions

Example 2:

Input: nums = [4,4,4], k = 3
Output: 0
Explanation: The subarrays of nums with length 3 are:
- [4,4,4] which does not meet the requirements because the element 4 is repeated.
We return 0 because no subarrays meet the conditions.

Constraints:

  • 1 <= k <= nums.length <= 105

  • 1 <= nums[i] <= 105


Topics: Array, Hashmap, Sliding Window

  • Static sliding window, calculate first k numbers, then start the loop with the rest of the windows, moving both left and right one after the other and calculating current sum

  • Calculate the maximum sum if there are no repeating numbers in current window

  • A window has repeating chars if len of dictionary tracking char counts != window len

  • Delete the dictionary key/value pair if count reaches 0


5
New cards

Longest Substring Without Repeating Characters

[Medium]

Given a string s, find the length of the longest substring without duplicate characters.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3. Note that "bca" and "cab" are also correct answers.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints:

  • 0 <= s.length <= 105

  • s consists of English letters, digits, symbols and spaces.


Topics: String, Sliding Window, Hashmap

  • Dynamic sliding window, moving left whenever current window has repeating

  • A window has repeating chars if len of dictionary tracking char counts != window len

  • Delete the dictionary key/value pair if count reaches 0


6
New cards

Merge Sorted Array

[Easy]

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.

Example 1:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

Example 2:

Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].

Example 3:

Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.

Constraints:

  • nums1.length == m + n

  • nums2.length == n

  • 0 <= m, n <= 200

  • 1 <= m + n <= 200

  • -109 <= nums1[i], nums2[j] <= 109

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

Topics: Array, Two Pointers

  • Start with pointers at the end of the non-zero data in each array, and a pointer at end of first array to track the next position

  • Compare each time array 1 to array 2, then place larger number into next position

  • The original moved numbers are eventually overwritten when next position pointer reaches it as it moves left

  • Add final loop at the end to check the remaining numbers inside array 2, if there are any left


7
New cards

Remove Duplicates from Sorted Array

[Easy]

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Consider the number of unique elements in nums to be k​​​​​​​​​​​​​​. After removing duplicates, return the number of unique elements k.

The first k elements of nums should contain the unique numbers in sorted order. The remaining elements beyond index k - 1 can be ignored.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will be accepted.

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

  • 1 <= nums.length <= 3 * 104

  • -100 <= nums[i] <= 100

  • nums is sorted in non-decreasing order.

Topics: Array, Two Pointers

  • Use the fact it is sorted in non-decreasing order to realize we can detect the boundaries between ranges of duplicate numbers by checking if they changed
  • One pointer tracks current next position, while the other goes to check at each boundary, and copy into the next position
  • We skip over index 0 as it is always unique and start at index 1
8
New cards

Two Sum II - Input Array Is Sorted

[Medium]

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

Example 1:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].

Example 2:

Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].

Example 3:

Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].

Constraints:

  • 2 <= numbers.length <= 3 * 104

  • -1000 <= numbers[i] <= 1000

  • numbers is sorted in non-decreasing order.

  • -1000 <= target <= 1000

  • The tests are generated such that there is exactly one solution.


Topics: Array, Two Pointers

  • Use two pointers starting at 0 and end of array

  • Each time we check if the current pair's sum is equal to target

  • We move left / right pointers depending on whether the current sum is greater or smaller than target

  • Moving left up results in a larger left, while moving right down results in a smaller right


9
New cards

Find Minimum in Rotated Sorted Array

[Medium]

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.

Example 1:

Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.

Example 2:

Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.

Example 3:

Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated 4 times.

Constraints:

  • n == nums.length

  • 1 <= n <= 5000

  • -5000 <= nums[i] <= 5000

  • All the integers of nums are unique.

  • nums is sorted and rotated between 1 and n times.


Topics: Array, Binary Search

  • If current is > the last number, then minimum must be on the right side of current

  • Use that condition for binary search, checking middle each time and moving left/right


10
New cards

Find First and Last Position of Element in Sorted Array

[Medium]

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

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]

Example 3:

Input: nums = [], target = 0
Output: [-1,-1]

Constraints:

  • 0 <= nums.length <= 105

  • -109 <= nums[i] <= 109

  • nums is a non-decreasing array.

  • -109 <= target <= 109


Topics: Array, Binary Search

  • Binary search for first position by moving left/right pointers until potential first is at >= target and right keeps moving down

  • Binary search for last position by moving left/right pointers until potential last is at <= target and left keeps moving up

  • When left is moving up but using left = middle, we should use upper middle (left+right+1)//2 so that left is not stuck in infinite loop with the left = middle condition (lower middle of 0 and 1 is 0) * Check for edge condition when array is empty


11
New cards

Binary Tree Level Order Traversal

[Medium]

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

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2:

Input: root = [1]
Output: [[1]]

Example 3:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].

  • -1000 <= Node.val <= 1000


  • We go level by level, so we must use BFS * Keep a queue, and while queue is not empty, check the queue's size for the size of the current level to traverse that level (current nodes in the queue), popping from queue and adding each node's children to queue each time to build the next level * At each level, append to an array to build the current level, then append to a result array after traversing each level


12
New cards

Flood Fill

[Easy]

You are given an image represented by an m x n grid of integers image, where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and color. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc].

To perform a flood fill:

  • Begin with the starting pixel and change its color to color.

  • Perform the same process for each pixel that is directly adjacent (pixels that share a side with the original pixel, either horizontally or vertically) and shares the same color as the starting pixel.

  • Keep repeating this process by checking neighboring pixels of the updated pixels and modifying their color if it matches the original color of the starting pixel.

  • The process stops when there are no more adjacent pixels of the original color to update.

Return the modified image after performing the flood fill.

Example 1:

Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2

Output: [[2,2,2],[2,2,0],[2,0,1]]

Explanation:

From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.

Note the bottom corner is not colored 2, because it is not horizontally or vertically connected to the starting pixel.

Example 2:

Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0

Output: [[0,0,0],[0,0,0]]

Explanation:

The starting pixel is already colored with 0, which is the same as the target color. Therefore, no changes are made to the image.

Constraints:

  • m == image.length

  • n == image[i].length

  • 1 <= m, n <= 50

  • 0 <= image[i][j], color < 216

  • 0 <= sr < m

  • 0 <= sc < n


  • Use dfs starting at (sr, sc), where we convert the color to the new color if it's matching the original color * Always check the neighbor's bounds before running dfs on it * If the neighbor of the current pixel is the original color, we convert it to the new color


13
New cards

Maximum Depth of Binary Tree

[Easy]

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.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

Constraints:

  • The number of nodes in the tree is in the range [0, 104].

  • -100 <= Node.val <= 100


  • Use dfs to traverse the binary tree, getting the height of each node using 1 + max heights of its children * Eventually, we reach the root's height, which is the max of the heights of its children


14
New cards

Number of Islands

[Medium]

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.

Example 1:

Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1

Example 2:

Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3

Constraints:

  • m == grid.length

  • n == grid[i].length

  • 1 <= m, n <= 300

  • grid[i][j] is '0' or '1'.


Topics: Array, Graph BFS, Matrix, Graph DFS

  • Run DFS at each cell of the grid, incrementing count if there's a 1

  • Within DFS, just traverse and fill up all the 1s with #s

  • Future runs of DFS in other cells will see #s on the 1s that got filled from islands being found


15
New cards

Word Search

[Medium]

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.

Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

Constraints:

  • m == board.length

  • n = board[i].length

  • 1 <= m, n <= 6

  • 1 <= word.length <= 15

  • board and word consists of only lowercase and uppercase English letters.

Follow up: Could you use search pruning to make your solution faster with a larger board?

Topics: Array, String, Backtracking, Matrix

  • DFS at each character in the board, pruning every time we find a character where the current index in the word does not match the current index of the current path

  • To prevent going to characters visited in current path, we change it to "#" to mark as visited before traversing the neighbors


16
New cards

K Closest Points to Origin

[Medium]

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

Example 1:

Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].

Example 2:

Input: points = [[3,3],[5,-1],[-2,4]], k = 2
Output: [[3,3],[-2,4]]
Explanation: The answer [[-2,4],[3,3]] would also be accepted.

Constraints:

  • 1 <= k <= points.length <= 104

  • -104 <= xi, yi <= 104


  • Use heapq to push every point to a heap, sorted by distance squared to origin * Pop k points from the resulting heap


17
New cards

Kth Largest Element in an Array

[Medium]

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5

Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

Constraints:

  • 1 <= k <= nums.length <= 105

  • -104 <= nums[i] <= 104


  • Push each element into a max heap (priority queue), then pop k times and return kth element


18
New cards

Remove Element

[Easy]

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.

  • Return k.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will be accepted.

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

  • 0 <= nums.length <= 100

  • 0 <= nums[i] <= 50

  • 0 <= val <= 100

  • Two pointers: reader scans every element, writer marks the next slot for a kept element
  • If nums[reader] != val, copy it to nums[writer] and advance writer
  • Return writer — the first writer elements are the answer, the rest is don't-care
19
New cards

Minimum Size Subarray Sum

[Medium]

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Example 1:

Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.

Example 2:

Input: target = 4, nums = [1,4,4]
Output: 1

Example 3:

Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0

Constraints:

  • 1 <= target <= 109

  • 1 <= nums.length <= 105

  • 1 <= nums[i] <= 104

Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).

  • Sliding window: expand right, adding nums[right] to a running sum
  • While sum >= target, record the window length (right - left + 1), then shrink from the left
  • Track the smallest length seen; return 0 if you never reach target
20
New cards

Minimum Absolute Difference in BST

[Easy]

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

Example 1:

Input: root = [4,2,6,1,3]
Output: 1

Example 2:

Input: root = [1,0,48,null,null,12,49]
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [2, 104].

  • 0 <= Node.val <= 105

Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/

Topics: Binary Tree BFS

  • Use binary search tree in-order traversal, by using recursion to explore left subtrees first, then recursively explore right subtrees (it pops up from the leftmost left, all the way back to root)
  • Min abs diff must always be adjacent to each other in sorted order (no number can sit between them) so update min each time by checking prev value
21
New cards

Convert Sorted Array to Binary Search Tree

[Easy]

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

Example 1:

Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:

Example 2:

Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.

Constraints:

  • 1 <= nums.length <= 104

  • -104 <= nums[i] <= 104

  • nums is sorted in a strictly increasing order.

Topics: Array, Divide & Conquer, Binary Search Tree, Binary Tree

  • Recursively pass in a range, and then find the middle between the current middle and the left, and the current middle and the right
  • Define the root (start of the recursion) and building the children up recursively in its definition
22
New cards

Search Insert Position

[Easy]

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.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [1,3,5,6], target = 5
Output: 2

Example 2:

Input: nums = [1,3,5,6], target = 2
Output: 1

Example 3:

Input: nums = [1,3,5,6], target = 7
Output: 4

Constraints:

  • 1 <= nums.length <= 104

  • -104 <= nums[i] <= 104

  • nums contains distinct values sorted in ascending order.

  • -104 <= target <= 104

Topics: Array, Binary Search

  • Left and right, with middle pointer, moving left to middle + 1 if middle is less than or equal to target and right to middle 1 if middle is greater than target
  • We check if middle is equal to target before moving left to middle + 1, because we used middle <= target
  • At the end, the index where target would be is at left if it's
23
New cards

Kth Smallest Element in a BST

[Medium]

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Example 1:

Input: root = [3,1,4,null,2], k = 1
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

Constraints:

  • The number of nodes in the tree is n.

  • 1 <= k <= n <= 104

  • 0 <= Node.val <= 104

Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

Topics: Binary Search Tree, Binary Tree DFS, Binary Tree

  • Use in-order traversal, which is basically DFS (going all the way down left until you can't, then process current node, then go right)
  • Increment the count each time between the recursive left and right DFS calls, checking count == k (you're traveling back up the tree here and processing current node)
  • BST ensures we are visiting nodes in ascending order
  • Need to return the result within the DFS so the value eventually propagates back up in the end
24
New cards

Longest Increasing Subsequence

[Medium]

Given an integer array nums, return the length of the longest strictly increasing subsequence.

Example 1:

Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

Example 2:

Input: nums = [0,1,0,3,2,3]
Output: 4

Example 3:

Input: nums = [7,7,7,7,7,7,7]
Output: 1

Constraints:

  • 1 <= nums.length <= 2500

  • -104 <= nums[i] <= 104

Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

Topics: Array, 1D DP

  • Bottom-up DP:
  • Subproblem where the longest increasing subsequence ending at current index = max(previous increasing subsequences where the next number could be the current index, aka ending at a number < current index)
  • At each index, we calculate the longest increasing subsequence, keeping track in an array
  • Return the max of the LIS for each index
  • Top-down DP:
  • At each index, calculate max LIS length for every index visited up to current index, and set current index's max LIS length to that + 1
  • Use memo to keep track of visited indices, returning immediately if already visited
  • Return the max of the LIS for each index
25
New cards

Linked List Cycle

[Easy]

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.

Example 1:

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

Example 2:

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.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Constraints:

  • The number of the nodes in the list is in the range [0, 104].

  • -105 <= Node.val <= 105

  • pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?

Topics: Linked List

  • Keep track of visited nodes in a set and check if each node has been visited while we traverse
26
New cards

Add Two Numbers

[Medium]

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.

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].

  • 0 <= Node.val <= 9

  • It is guaranteed that the list represents a number that does not have leading zeros.

Topics: Linked List

  • Traverse both linked lists while either one or the other node exists or if carry over > 0, and for either node, add it and the carry over to the current sum digit
  • Set the current new node to current sum % 10
  • Keep track of carry over amount at the end to use in next digit by calculating current sum // 10
  • Use a dummy node to point to our new list's head, returning it at the end; each new digit gets a new ListNode created, so the first node has empty value pointing to our first digit
27
New cards

Valid Sudoku

[Medium]

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.

Example 1:

Input: board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true

Example 2:

Input: board =
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

Constraints:

  • board.length == 9

  • board[i].length == 9

  • board[i][j] is a digit 1-9 or '.'.


Topics: Array, Hashmap, Matrix

  • Keep track of visited rows, columns, and boxes in lists of hash sets

  • As you traverse each cell, check if they already exist in the hash set at that row, column, and box

  • If not, add them to the hash sets for that row, column, and box

  • You get the index of the box by taking the row index, integer divide by 3 to get the box row, then multiply by 3 to get the actual first box number in that row, and then add the column index integer divide by 3 to move to the correct box in that row


28
New cards

Ransom Note

[Easy]

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

Constraints:

  • 1 <= ransomNote.length, magazine.length <= 105

  • ransomNote and magazine consist of lowercase English letters.


Topics: String, Hashmap

  • Keep track of count of characters inside magazine in a hash table / dictionary

  • For each character in ransom note, decrement the character count in magazine if found, and return false if doesn't exist

  • When count reaches 0, remember to delete the character from the dictionary (in Python)


29
New cards

Majority Element

[Easy]

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.

Example 1:

Input: nums = [3,2,3]
Output: 3

Example 2:

Input: nums = [2,2,1,1,1,2,2]
Output: 2

Constraints:

  • n == nums.length

  • 1 <= n <= 5 * 104

  • -109 <= nums[i] <= 109

  • The input is generated such that a majority element will exist in the array.

Follow-up: Could you solve the problem in linear time and in O(1) space?

Topics: Array, Hashmap

  • Keep track of count of numbers in a hash table / dictionary
  • If count of a number is > length of nums // 2, return the number
30
New cards

Rotate Array

[Medium]

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

Example 1:

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]

Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Constraints:

  • 1 <= nums.length <= 105

  • -231 <= nums[i] <= 231 - 1

  • 0 <= k <= 105

Follow up:

  • Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.

  • Could you do it in-place with O(1) extra space?

Topics: Array, Two Pointers, Math

  • To achieve O(1) extra space, the trick is that when we rotate the array, the last k % n positions get pushed to the start of the array
  • First, use two pointers to reverse the entire array
  • Then we can simply reverse the first k % n elements to get the order of the rotated array, then reverse from the k % n + 1 element to the end
31
New cards

Best Time to Buy and Sell Stock

[Easy]

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.

Example 1:

Input: prices = [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.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

  • 1 <= prices.length <= 105

  • 0 <= prices[i] <= 104

Topics: Array

  • One method is to track current min price so far from previous days, and current max profit possible using min price so far, then keep track of the overall max profit
  • Dynamic programming method: think like mathematical induction. Base case is minPrice = price[0], maxProfit = 0, inductive step is minPrice = min(price[k], minPrice), maxProfit = max(maxProfit[k-1], price[k] minPrice)
32
New cards

Valid Parentheses

[Easy]

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.

  • Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = "()"

Output: true

Example 2:

Input: s = "()[]{}"

Output: true

Example 3:

Input: s = "(]"

Output: false

Example 4:

Input: s = "([])"

Output: true

Example 5:

Input: s = "([)]"

Output: false

Constraints:

  • 1 <= s.length <= 104

  • s consists of parentheses only '()[]{}'.

Topics: String, Stack

  • Use a stack, popping if latest item in stack has a matching start bracket, appending if not
33
New cards

Binary Tree Right Side View

[Medium]

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.

Example 1:

Input: root = [1,2,3,null,5,null,4]

Output: [1,3,4]

Explanation:

Example 2:

Input: root = [1,2,3,4,null,null,null,5]

Output: [1,3,4,5]

Explanation:

Example 3:

Input: root = [1,null,3]

Output: [1,3]

Example 4:

Input: root = []

Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 100].

  • -100 <= Node.val <= 100

Topics: Binary Tree BFS, Binary Tree

  • Use a queue with deque() to do binary tree BFS (level-order traversal), appending the rightmost node at every level to our result list
  • While loop checks for queue existance, where the queue during each iteration represents the current level
  • In each while loop iteration, loop through the queue, using popleft to pop the leftmost item each time
34
New cards

Best Time to Buy and Sell Stock II

[Medium]

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 sell and buy the stock multiple times on the same day, ensuring you never hold more than one share of the stock.

Find and return the maximum profit you can achieve.

Example 1:

Input: prices = [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.
Total profit is 4 + 3 = 7.

Example 2:

Input: prices = [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.
Total profit is 4.

Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.

Constraints:

  • 1 <= prices.length <= 3 * 104

  • 0 <= prices[i] <= 104

Topics: Array, 1D DP

  • Buy and sell for every single day that has a price higher than the previous day, adding all the profit to the max profit
  • Dynamic programming?
35
New cards

Is Subsequence

[Easy]

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Example 1:

Input: s = "abc", t = "ahbgdc"
Output: true

Example 2:

Input: s = "axc", t = "ahbgdc"
Output: false

Constraints:

  • 0 <= s.length <= 100

  • 0 <= t.length <= 104

  • s and t consist only of lowercase English letters.

Follow up: Suppose there are lots of incoming s, say s1, s2, …, sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?

Topics: String, Two Pointers, 1D DP

  • One pointer keeps track of current visited chars in s, while the other traverses t, moving the s pointer every time it visits a character in t equal to s
  • If the s pointer reaches an index out of bounds, then return True (we encountered all the chars of s in the correct order inside t)
  • If s pointer doesn't reach the end after traversing t, return False
  • Dynamic programming?
36
New cards

Container With Most Water

[Medium]

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.

Notice that you may not slant the container.

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: 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 2:

Input: height = [1,1]
Output: 1

Constraints:

  • n == height.length

  • 2 <= n <= 105

  • 0 <= height[i] <= 104

Topics: Array, Two Pointers

  • Use two pointers, one at start and one at end, moving inwards while left < right
  • We move the shorter pointer inward each time, as moving the taller pointer can never increase the area (height capped by the shorter pointer)
  • Calculate current area = min(height[left], height[right]) * (right - left) and keep track of the max area
37
New cards

Validate Binary Search Tree

[Medium]

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 strictly less than the node's key.

  • The right subtree of a node contains only nodes with keys strictly greater than the node's key.

  • Both the left and right subtrees must also be binary search trees.

Example 1:

Input: root = [2,1,3]
Output: true

Example 2:

Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

Constraints:

  • The number of nodes in the tree is in the range [1, 104].

  • -231 <= Node.val <= 231 - 1

Topics: Binary Tree, Binary Tree DFS, Binary Search Tree

  • At every node, we check if it is valid given a minimum and maximum boundary
  • Recursively check validity of left and right children, passing in min and max values from the current node's value based on the binary tree condition
  • Base case empty node is considered valid
38
New cards

Length of Last Word

[Easy]

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Constraints:

  • 1 <= s.length <= 104

  • s consists of only English letters and spaces ' '.

  • There will be at least one word in s.

Topics: String

  • Traverse with pointer starting at end, ignoring the spaces at end, starting count when encountering the last word, then ending count upon detecting spaces or reaching start of the string
39
New cards

Find the Index of the First Occurrence in a String

[Easy]

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.

Example 1:

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.

Example 2:

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.

Constraints:

  • 1 <= haystack.length, needle.length <= 104

  • haystack and needle consist of only lowercase English characters.

Topics: String

  • Traverse the string while needle ptr != len(needle) and haystack ptr != len(haystack) * If both needle ptr and haystack ptr match characters, we record first index if it's None, then traverse both of them * If needle ptr and haystack ptr don't match, we revert haystack ptr back to where first was + 1 if first is not None, else if first is None then we traverse haystack ptr (no matches here so move on), then reset both the needle ptr and first to None
40
New cards

Isomorphic Strings

[Easy]

Given two strings s and t, determine if they are isomorphic.

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

Example 1:

Input: s = "egg", t = "add"

Output: true

Explanation:

The strings s and t can be made identical by:

  • Mapping 'e' to 'a'.

  • Mapping 'g' to 'd'.

Example 2:

Input: s = "f11", t = "b23"

Output: false

Explanation:

The strings s and t can not be made identical as '1' needs to be mapped to both '2' and '3'.

Example 3:

Input: s = "paper", t = "title"

Output: true

Constraints:

  • 1 <= s.length <= 5 * 104

  • t.length == s.length

  • s and t consist of any valid ascii character.

Topics: Hashmap

  • Create two hash maps to map characters from s to t and t to s * Return false if len(s) != len(t) * Traverse both strings at once, checking if the mappings exist yet, then check if the mappings match * Else the mappings don't exist yet, we set the mappings
41
New cards

Roman to Integer

[Easy]

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

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints:

  • 1 <= s.length <= 15

  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').

  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

Topics: String, Hashmap, Math

  • Use a hash map to map integer values to roman numerals
  • Traverse each roman numeral in the string and add to running total, but subtract from running total if the current numeral is less than the next numeral
42
New cards

Search a 2D Matrix

[Medium]

You are given an m x n integer matrix matrix with the following two properties:

  • Each row is sorted in non-decreasing order.

  • The first integer of each row is greater than the last integer of the previous row.

Given an integer target, return true if target is in matrix or false otherwise.

You must write a solution in O(log(m * n)) time complexity.

Example 1:

Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true

Example 2:

Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false

Constraints:

  • m == matrix.length

  • n == matrix[i].length

  • 1 <= m, n <= 100

  • -104 <= matrix[i][j], target <= 104

Topics: Array, Matrix, Binary Search

  • Treat the 2D matrix as a 1D array, fetching the middle value using row = mid // n, col = mid % n
  • Use an exact match binary search with while left <= right, and right = mid-1 and left = mid+1 updates
43
New cards

Word Pattern

[Easy]

Given a pattern and a string s, find if s follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. Specifically:

  • Each letter in pattern maps to exactly one unique word in s.

  • Each unique word in s maps to exactly one letter in pattern.

  • No two letters map to the same word, and no two words map to the same letter.

Example 1:

Input: pattern = "abba", s = "dog cat cat dog"

Output: true

Explanation:

The bijection can be established as:

  • 'a' maps to "dog".

  • 'b' maps to "cat".

Example 2:

Input: pattern = "abba", s = "dog cat cat fish"

Output: false

Example 3:

Input: pattern = "aaaa", s = "dog cat cat dog"

Output: false

Constraints:

  • 1 <= pattern.length <= 300

  • pattern contains only lower-case English letters.

  • 1 <= s.length <= 3000

  • s contains only lowercase English letters and spaces ' '.

  • s does not contain any leading or trailing spaces.

  • All the words in s are separated by a single space.

  • Use 2 hash maps to map pattern letters to words and words to pattern letters * If length of pattern and number of words in the string do not match, return false * Traverse each letter in the pattern, adding to both hash maps if not visited, then checking if pattern already visited whether both hash maps match
44
New cards

Simplify Path

[Medium]

You are given an absolute path for a Unix-style file system, which always begins with a slash '/'. Your task is to transform this absolute path into its simplified canonical path.

The rules of a Unix-style file system are as follows:

  • A single period '.' represents the current directory.

  • A double period '..' represents the previous/parent directory.

  • Multiple consecutive slashes such as '//' and '///' are treated as a single slash '/'.

  • Any sequence of periods that does not match the rules above should be treated as a valid directory or file name. For example, '…' and '….' are valid directory or file names.

The simplified canonical path should follow these rules:

  • The path must start with a single slash '/'.

  • Directories within the path must be separated by exactly one slash '/'.

  • The path must not end with a slash '/', unless it is the root directory.

  • The path must not have any single or double periods ('.' and '..') used to denote current or parent directories.

Return the simplified canonical path.

Example 1:

Input: path = "/home/"

Output: "/home"

Explanation:

The trailing slash should be removed.

Example 2:

Input: path = "/home//foo/"

Output: "/home/foo"

Explanation:

Multiple consecutive slashes are replaced by a single one.

Example 3:

Input: path = "/home/user/Documents/../Pictures"

Output: "/home/user/Pictures"

Explanation:

A double period ".." refers to the directory up a level (the parent directory).

Example 4:

Input: path = "/../"

Output: "/"

Explanation:

Going one level up from the root directory is not possible.

Example 5:

Input: path = "/…/a/../b/c/../d/./"

Output: "/…/b/d"

Explanation:

"…" is a valid name for a directory in this problem.

Constraints:

  • 1 <= path.length <= 3000

  • path consists of English letters, digits, period '.', slash '/' or '_'.

  • path is a valid absolute Unix path.

  • Split the path files/directories by "/" * If a file/directory name is "." or "", we ignore it * If a name is "..", we then check if the stack length > 0 and if so then we pop from the stack * Else, we append the name to the stack * At the end, return "/" + "/".join(stack)
45
New cards

Valid Anagram

[Easy]

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Example 1:

Input: s = "anagram", t = "nagaram"

Output: true

Example 2:

Input: s = "rat", t = "car"

Output: false

Constraints:

  • 1 <= s.length, t.length <= 5 * 104

  • s and t consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

  • Use hash map to increment count of each character in one string (initialize hash map with defaultdict) * Traverse each character in other string and subtract count from each char found in the hash map, returning false if it's not in there * Remember to delete from hash map if count reaches 0 * If length of two strings are not equal, return fals