Blind Curated 74 Problems Flashcards

1
Q

Two Sum

A

Store the array in a map. If Sum - arr[i] exists in the array, then return arr[i] and Sum - arr[i]

TC:
SC:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Longest Substring Without Repeating Characters

A

Window Expand — Until a repeated character is found.
Contract Window — i = Math.max(index(j), i);

        if(indices[s.charAt(j)] != -1) {
            i = Math.max(indices[s.charAt(j)] + 1, i);   
        }
            maxLength = Math.max(maxLength, j - i + 1);
            indices[s.charAt(j)] = j;

TC:
SC:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Longest Palindromic Substring

A
int len1 = expandAroundCenter(s, i, i);
        int len2 = expandAroundCenter(s, i, i + 1);
        int len = Math.max(len1, len2);
        // Find the boundaries of the palindrome
        if (len > end - start) {
            start = i - (len - 1) / 2;
            end = i + len / 2;
}

TC:
SC:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Container With Most Water

https://leetcode.com/problems/container-with-most-water/

A

Two pointer approach. Move the pointer which has the minimum height between the two pointers forward

TC: O(N)
SC: O(1) -> No extra space.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

3Sum

A

for every i find a pair in the array such that

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Remove Nth Node From End of List

A

FirstNode = Head; SecondNode = Head

Advance the first node by N positions. Then move both pointers — first and second —until the first pointer reaches the end of the list.

TC:
SC:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Merge K Sorted Lists

https://leetcode.com/problems/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.

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
A

Revisit the solution for Divide and Conquer Approach

https://www.youtube.com/watch?v=OaPaTaj0xYo&ab_channel=jayatitiwari

TC:
SC:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Search in Rotated Sorted Array

A

Find the pivot in the array — Smallest element in the array. Binary Search in right if the element is in the right half, else search in the left half of the array.

TC:
SC:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Combination Sum I

https://leetcode.com/problems/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.

It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

A
backtrack(int [] candidates, 
      LinkedList temp, 
      List> output, 
      int start, 
      int target) {
// Base case

for(int j = start; j < candidates.length; j++) {
temp.add(candidates[j]);
backtrack(candidates, temp, output, j, target - candidates[j]);
temp.removeLast();
}
}

TC:
SC:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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.

Note: The solution set must not contain duplicate combinations.

https://leetcode.com/problems/combination-sum-ii/

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: 
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
A
for(int i = start; i < candidates.size(); i++) {
            // Frequency 
            int[] currentCandidate = candidates.get(i);
            int candidateValue = currentCandidate[0];
            int frequency = currentCandidate[1];
        if(frequency <= 0)
            continue;

        temp. add(candidateValue);
        candidates. set(i, new int[]{candidateValue, frequency - 1});
            // Continue exploration
            backtrack(candidates, temp, output, remainingSum - candidateValue, i);
        candidates.set(i, new int[]{candidateValue, frequency});
        temp.removeLast();
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Combination Sum ||| —Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

Only numbers 1 through 9 are used.
Each number is used at most once.
Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

https://leetcode.com/problems/combination-sum-iii/

Input: k = 3, n = 7
Output: [[1,2,4]]
Explanation:
1 + 2 + 4 = 7
There are no other valid combinations.
Input: k = 3, n = 9
Output: [[1,2,6],[1,3,5],[2,3,4]]
Explanation:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.
A

Apply CombinationSum1 problem on the array [1,2,3,4,5,6,7,8,9].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Combination Sum IV — Dynamic programming

https://leetcode.com/problems/combination-sum-iv/solution/

Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.

The answer is guaranteed to fit in a 32-bit integer.

Input: nums = [1,2,3], target = 4
Output: 7
Explanation:
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
A

TBD

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

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 neighbors;
}

Test case format:

For simplicity, each node’s value is the same as the node’s index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.

A

Q -> Data structure to store the nodes for which the clones aren’t created yet.
VisitedMa Nodes for which clones were created.

while(!q.isEmpty()) {
          // Pop element from the queue
          Node temp = q.remove();
          for(Node neighbor: temp.neighbors) {
            if(!visited.containsKey(neighbor)) {
                // Clone the neighbor and add a mapping in the visited map.
                visited.put(neighbor, new Node(neighbor.val, new ArrayList()));
            q.add(neighbor);
        }
        // The clones of neighbors have just been created above. If the clone of temp has already
        // been created, then create edges between the clone of temp and clone of neighbors of temp.
        if(visited.containsKey(temp)) 
            visited.get(temp).neighbors.add(visited.get(neighbor));
      } }

TC: O(V + E)
SC: O(V)

V - Number of Vertices
E - Number of Edges.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Clone Graph DFS

A
public Node cloneGraphDFS(Node node) {
        // Base case
        if(node == null)
            return node;
        // If the node is already visited/ it's clone has been created before, then return the deep copy of the node.
        if(visited.containsKey(node))
            return visited.get(node);
        // Create a clone of the node 
        Node nodeClone = new Node(node.val, new ArrayList());
        // Mark the node as visited
        visited.put(node, nodeClone);
        // Recursively create clones of the neighbors of the node.
        for(Node neighbor: node.neighbors) {
            nodeClone.neighbors.add(cloneGraphDFS(neighbor));
        }
    return nodeClone;
}

TC: O(V + E)
SC: O(V)

V - Number of Vertices
E - Number of Edges.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Course Schedule

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.

Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.

A
  1. Build the Graph Adjacency List.
  2. Traverse the graph with each node of the graph as the starting node. Leaves breadcrumbs along the path and if you come across a node which has was visited before, then there exists a cycle in the graph.

For code: https://leetcode.com/problems/course-schedule/solution/

TC: E + V^2
SC: E + V

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Course Schedule Topological Sort

https://leetcode.com/problems/course-schedule/

A

Two approaches:
1. DFS approach
a. With each node as the starting node, traverse the graph to check if a cycle exists in the graph.
b. Cycle detection using DFS:
isCycle(traversalPath, node, adjacency List) {
// Return false if the node isn’t present in the adjacency list.
// Return true if the node is visited already.
// Visit the node. traversalPath[node] = true;
// Recursively visit the neighboring nodes
// Set the node as node as unvisited while backtracking. traversalPath[node] == false;

} 2. Topological sort.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Number of Islands

https://leetcode.com/problems/number-of-islands/submissions/

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.

Input: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1
A
  1. Iterate through the matrix
  2. If you encounter a one, then explore the island which the one is a part of. Mark the visited nodes as zero
  3. Counter the number of root nodes which that trigger DFS. Return this number after the exploration of the matrix.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Longest Consecutive Sequence
https://leetcode.com/problems/longest-consecutive-sequence/

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

You must write an algorithm that runs in O(n) time.

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

A
  1. Store the elements in a HashSet
  2. Look for the minimum element arr[i] in the consecutive sequence
  3. Update the maximum length based on the length of the increasing subsequence recorded with arr[i] as the starting element.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Course Schedule

https://leetcode.com/problems/course-schedule/solution/

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.

Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.

A
  1. Identify nodes with InDegree == 0 — no prerquisites and add them to the global order.
    1. Remove the edges between such nodes and their dependencies.
    2. Repeat Step 1) until there are no nodes without prerequisites left.
    3. If there are still some left edges left in the graph, then there exists a cycle in the graph.
    4. Otherwise, all of the edges were removed from the graph, return the global
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q
  1. Alien Dictionary
A
  1. Build the AdjacenyList and the IndegreeMap
    Map> adjacenyList = new HashMap<>();
    Map indegree = new HashMap<>();
  2. Compare the each word to the subsequent word and build out the character relations
  3. BFS
    a. Add all nodes with indegree 0 to the queue
    b. Pop the head from queue, let’s call it ‘node’ and append it to the output string.
    c. Remove all the edges between the node and it’s adjacent elements
    d. Repeat steps a through c until the queue is empty.
  4. Return the output string.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q
  1. Number of Connected Components in an Undirected Graph
A
  1. Everyone is their own representative initially and the total families would be equal to the number of individuals.
  2. Iterate through the relationships of the family.
  3. For every relationship, determine if sub-families can be combined into a larger family, and combine if they can be.
  4. Decrement the total family count if a merge is made
  5. Return the total number of families after the merge.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Graph Valid Tree

https://leetcode.com/problems/graph-valid-tree/submissions/

You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and a list of edges where edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the graph.

Return true if the edges of the given graph make up a valid tree, and false otherwise.

Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true

Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false

A

Iterative DFS:
1. Build the Adjacency list
adjacencyList.get(edge[0]).add(edge[1]);
adjacencyList.get(edge[1]).add(edge[0]);
2. Add the node 0 to a stack
3. Pop the top of the stack, let’s call it node.
4. Check if the neighbors of the node are seen:
a. If the neighbor is seen, then return false.
b. If the neighbor is not seen, then add it to the seen set.
c. Remove the edge neighbor -> node
5. If the number of elements in the seen set is <= n, then the graph is not a tree — as it is not fully connected.

Union Find:

  1. Everyone is their own representative initially and the total families would be equal to the number of individuals.
  2. Iterate through the relationships of the family.
  3. For every relationship, determine if sub-families can be combined into a larger family, and combine if they can be.
  4. Decrement the total family count if a merge is made
  5. Return the total number of families after the merge.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Coin Change

https://leetcode.com/problems/coin-change/

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Input: coins = [1], amount = 0
Output: 0

A
private int coinChangeBottomUp(int[] coins, int amount, int[] storage) {
        int[] memory = new int[amount + 1];
        // Fill the memory with default values
        Arrays.fill(memory, amount + 1);
        // Base case 
        memory[0] = 0;
    for(int i = 0; i <= amount; i++) {
        int minCoins = Integer.MAX_VALUE;
        for(int coin: coins) {
            if(i - coin >= 0) {
                memory[i] = Math.min(memory[i], 1 + memory[i - coin]);
            }
        }
    }

    return memory[amount] > amount ? -1: memory[amount];
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

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

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

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.

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

A
for(int i = 1; i < nums.length; i++) {
            int result = 0;
            for(int j = 0; j < i; j++) {
                // Check if nums[i] > nums[j] 
                if(nums[i] > nums[j]) {
                    //dp[i] = Math.max(dp[i], 1 + dp[j]);
                    //result = Math.max(result, dp[i]);
                    result = Math.max(result, dp[j]);
                }
            dp[i] = 1 + result;
            endResult = Math.max(endResult, dp[i]);
        }
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Reverse Linked List

https://leetcode.com/problems/reverse-linked-list/

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

A
  1. Two pointers appraoch
  2. Recursive reversal
// Figure out the recursion for three elements:
reverse(LinkedList head) {
   // Base case
  if(head == null || head.next == null)
        return head;

ListNode p = reverse(head.next);

head. next.next = head;
head. next = null;

return p
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Linked List Cycle

https://leetcode.com/problems/linked-list-cycle/

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

A
  1. Two pointers, pointer1 at x pace, pointer2 at 2x pace, if they ever meet then there is a cycle.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

https://leetcode.com/problems/merge-two-sorted-lists/

A

1->2->3

4->5>6

temp->1->2->3->4->5->6

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Merge k Sorted Lists

https://leetcode.com/problems/merge-k-sorted-lists/solution/

A

TC: O(KN)
SC: O(1)

ListNode output;

mergeKSortedLists() {
for(int i = 1…NthList)
ListNode output = mergeTwoSortedLists(output, i);
}

return output;

TC: O(Nlogk)
SC: O(1)

TBD

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Remove Nth Node From End of List

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

A
  1. Advances first pointer so that the gap between first and second is n nodes apart
  2. Move first to the end, maintaining the gap
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

https://leetcode.com/problems/reorder-list/

A
1. Find the middle node of the list
// 1->2->3->4->5->6
  1. Reverse the second half of the list
  2. Merge the two halves.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Set Matrix Zeroes

Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.

A
  1. Traverse through each call in the matrix
    a. If any of the cell contains a zero, then set the first element in the row and column to zero
  2. Traverse the matrix and set the element to zero if the either the matrix[0][i] or matrix[i][0] is zero.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

https://leetcode.com/problems/spiral-matrix/

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

A
  1. Add the top row to the output
  2. Add the right column to the output
  3. Add the bottom row to the output
  4. Add the left column to the output.
while(r1 <= r2 && c1 <= c2) {
            // Add the top row to the output.
            for(int c = c1; c <= c2; c++) output.add(matrix[r1][c]);
            // Add the right column to the output.
            for(int r = r1 + 1; r <= r2; r++) output.add(matrix[r][c2]);
            if(r1 < r2 && c1 < c2) {
                // Add the botton row to the output.
                for(int c = c2 -1; c >= c1; c--) output.add(matrix[r2][c]);
                // Add the left column to the output.
                for(int r = r2 - 1; r > r1; r--) output.add(matrix[r][c1]);
            }
            r1++;
            c1++;
            r2--;
            c2--;    
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Word Search

https://leetcode.com/problems/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.

A

[[“A”,”B”,”C”,”E”],
[“S”,”F”,”C”,”S”],
[“A”,”D”,”E”,”E”]],
word = “ABCCED”

  protected boolean backtrack(int row, int col, String word, int index) {
    /* Step 1). check the bottom case. */
    if (index >= word.length())
      return true;
    /* Step 2). Check the boundaries. */
    if (row < 0 || row == this.ROWS || col < 0 || col == this.COLS
        || this.board[row][col] != word.charAt(index))
      return false;
    /* Step 3). explore the neighbors in DFS */
    boolean ret = false;
    // mark the path before the next exploration
    this.board[row][col] = '#';
    int[] rowOffsets = {0, 1, 0, -1};
    int[] colOffsets = {1, 0, -1, 0};
    for (int d = 0; d < 4; ++d) {
      ret = this.backtrack(row + rowOffsets[d], col + colOffsets[d], word, index + 1);
      if (ret)
        break;
    }
    /* Step 4). clean up and return the result. */
    this.board[row][col] = word.charAt(index);
    return ret;
  }
34
Q
  1. Longest Repeating Character Replacement
    https: //leetcode.com/problems/longest-repeating-character-replacement/

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations.

Input: s = “ABAB”, k = 2
Output: 4
Explanation: Replace the two ‘A’s with two ‘B’s or vice versa.

A
  1. Expand the window until at most K operations are used up.
  2. Update the maximum length of the window with at most K non-repeating characters
  3. Return the length of the maximum window with at most K non-repeating characters.

for(int windowEnd = 0, windowStart = 0; windowEnd < sLength; windowEnd++) {
maxCountOfRepeatingCharacters = Math.max(maxCountOfRepeatingCharacters, ++charCount[s.charAt(windowEnd) - ‘A’]);

       while(maxCountOfRepeatingCharacters + k < windowEnd - windowStart + 1) {
           charCount[s.charAt(windowStart++) - 'A']--;
       }

       result = Math.max(result, windowEnd - windowStart + 1); }
35
Q

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.

https://leetcode.com/problems/minimum-window-substring/

Input: s = “ADOBECODEBANC”, t = “ABC”
Output: “BANC”
Explanation: The minimum window substring “BANC” includes ‘A’, ‘B’, and ‘C’ from string t.

Input: s = “a”, t = “a”
Output: “a”
Explanation: The entire string s is the minimum window.

A
s = "ADOBECODEBANC"
t = "ABC"
  1. Expand the window until a valid window is found — contains all the characters of t.
  2. Contract the window until the window remains valid
    a. Update the minimum length of the window identified so-far.

Return the Minimum length of the window identified.

36
Q

Group Anagrams

https://leetcode.com/problems/group-anagrams/

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

A
  1. Generate hashes using the character count array.
    StringBuilder sb = new StringBuilder();
    for(int each: charCount) {
    sb.append(each);
    sb.append(‘#’);
    }

Map> map = new ArrayList>

  1. Return new ArrayList<>(map.values());
37
Q

Valid Parentheses

https://leetcode.com/problems/valid-parentheses/

A

Iterate throughs the characters of the String S:

  1. If the character s.charAt(i) is a open bracket — push into the stack
  2. If the character s.chatAt(i) isn’t an opening bracket of the same type, then return false.
  3. Return the
38
Q

Valid Palindrome

https://leetcode.com/problems/valid-palindrome/

A
  1. Two pointers, one from the start of the array, one at the end of the array.
  2. Skip everything else expect for Alphanumeric characters.

while (i < j && !Character.isLetterOrDigit(s.charAt(i))) {
i++;
}

while (i < j && !Character.isLetterOrDigit(s.charAt(j))) {
j–;
}

39
Q

Longest Common Subsequence

https://leetcode.com/problems/longest-common-subsequence/

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

For example, “ace” is a subsequence of “abcde”.
A common subsequence of two strings is a subsequence that is common to both strings.

Example 1:

Input: text1 = “abcde”, text2 = “ace”
Output: 3
Explanation: The longest common subsequence is “ace” and its length is 3.
Example 2:

Input: text1 = “abc”, text2 = “abc”
Output: 3
Explanation: The longest common subsequence is “abc” and its length is 3.

A

Would a Greedy approach lead to an Optimal solution? — No

Let’s start with a recursive solution:

    public int LCS(String a, String b) {
       // Base case 
       if(a.length() == 0 || b.length() == 0)
            return 0;
       // Search for a.charAt(i) in b
       // Figure out the first occurance of a.charAt(i) in b.
        int fo = fisrtOccurance(a.charAt(i));
    if(check if fo exists in b)
        int firstPossibility = 1 + LCS(a.substring(1), b.subsstring(fo + 1)); 

    int secondPossibility =  LCS(a.substring(1), b);

    return Math.max(firstPossibility, secondPossibility);  }

However, the above solution would result in overlapping subproblems. Hence, we can memoize the results of the overlapping subproblems.

        // if the subproblem is solved already.
        if(memo[p1][p2] != -1)
            return memo[p1][p2];
        // Figure out the first occurance of text1.charAt(i) in text2.
        int firstOccurance = -1;
        for(int i = p2; i < text2.length(); i++) {
            if(text1.charAt(p1) == text2.charAt(i)) {
                firstOccurance = i;
                break;
            }
        }
    int firstPossibility = helper(p1 + 1, p2, text1, text2);

    int secondPossibility = -1;
    if(firstOccurance != -1)
        secondPossibility = 1 + helper(p1 + 1, firstOccurance + 1, text1, text2);

    memo[p1][p2] = Math.max(firstPossibility, secondPossibility);

There is another method of diving the problem into sub-problems:

        if(text1.charAt(p1) == text2.charAt(p2)) {
            result = 1 + helper(p1 + 1, p2 + 1, text1, text2);
        } else {
            result = Math.max(helper(p1, p2 + 1, text1, text2), helper(p1 + 1, p2, text1, text2));
        }

The above method will translate more easily into the bottom-up solution:

    // Iterate up each column, starting from the last one.
    for (int col = text2.length() - 1; col >= 0; col--) {
      for (int row = text1.length() - 1; row >= 0; row--) {
        // If the corresponding characters for this cell are the same...
        if (text1.charAt(row) == text2.charAt(col)) {
          dpGrid[row][col] = 1 + dpGrid[row + 1][col + 1];
        // Otherwise they must be different...
        } else {
          dpGrid[row][col] = Math.max(dpGrid[row + 1][col], dpGrid[row][col + 1]);
        }
      }
    }
40
Q

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.

https://leetcode.com/problems/word-break/

A

TBD

41
Q

Palindromic Substrings

Given a string s, return the number of palindromic substrings in it.

A string is a palindrome when it reads the same backward as forward.

A substring is a contiguous sequence of characters within the string.

https://leetcode.com/problems/palindromic-substrings/

Input: s = “abc”
Output: 3
Explanation: Three palindromic strings: “a”, “b”, “c”.

A

for(int i = 0; i < s.length(); i++) {
counter += expandFromMiddle(s, i, i);

counter += expandFromMiddle(s, i, i +1);
}

42
Q

Encode and Decode Strings

https://leetcode.com/problems/encode-and-decode-strings/

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Machine 1 (sender) has the function:

string encode(vector strs) {
  // ... your code
  return encoded_string;
}
Machine 2 (receiver) has the function:
vector decode(string s) {
  //... your code
  return strs;
}
So Machine 1 does:

string encoded_string = encode(strs);
and Machine 2 does:

vector strs2 = decode(encoded_string);
strs2 in Machine 2 should be the same as strs in Machine 1.

Implement the encode and decode methods.

You are not allowed to solve the problem using any serialize methods (such as eval).

A
  1. How should the encoding be done?
  2. The strings can’t be tied together with a delimiter in the ASCII character set.
  3. Can a UTF-8 character set be used?

Encode:

String delimeter = Character.toString((char)257);
String emptyCharacterProxy = Character.toString((char)258);

for(String value: strs) {
   if(value.equals("")) 
      sb.append(emptyCharacterProxy);
   else
      sb.append(value);

sb.append(delimeter);
}

Decode:

String[] sArray = s.split(delimeter);

for(String each: sArray) {
if(each.equals(emptyCharacterProxy))
    output.add("");
else
    output.add(each);
}
43
Q
  1. Maximum Depth of Binary Tree

https: //leetcode.com/problems/maximum-depth-of-binary-tree/

A
// Compute the depth of the left subtree
int leftDepth = maxDepth(root.left);
// Compute the depth of the right subtree
int rightDepth = maxDepth(root.right);
// Return the maximum depth between the two.        
return Math.max(leftDepth, rightDepth) + 1;
44
Q

Same Tree

https://leetcode.com/problems/same-tree/

A

if(p == null && q == null)
return true;

if(p == null || q == null)
return false;

if(p.val != q.val)
return false;

// Recursively compare the left and the right subtrees.        
return compareTrees(p.left, q.left) && compareTrees(p.right, q.right);
45
Q

Invert a Binary Tree

https://leetcode.com/problems/invert-binary-tree/

A
public TreeNode invertTree(TreeNode root) {
        if(root == null)
            return root;
       // Swap the left and the right links.
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
   // Recursively invert left and right sub-trees. 
    invertTree(root.left);
    invertTree(root.right);

    return root;
}
46
Q

Binary Tree Maximum Path Sum

https://leetcode.com/problems/binary-tree-maximum-path-sum/

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path.

Given the root of a binary tree, return the maximum path sum of any path.

A
// Compute the max gain from the left sub-tree
int leftMaxGain = Math.max(maxgain(node.left, result), 0);
int rightMaxGain = Math.max(maxgain(node.right, result), 0);
        // New path price where node is the highest node.
        int newPathPrice = node.val + leftMaxGain + rightMaxGain;
// Update if newPathPrice is greater.
result.result = Math.max(result.result, newPathPrice);
// Return the max gain from this node.
return node.val + Math.max(leftMaxGain, rightMaxGain);
47
Q

Binary Tree Level Order Traversal

https://leetcode.com/problems/binary-tree-level-order-traversal/

A
// Base case
        if(root == null)
            return;
    if(level == output.size()) {
        output.add(level, new ArrayList<>());
    }

    output.get(level).add(root.val);

    level(root.left, level + 1);
    level(root.right, level + 1);
48
Q

Word Break

https://leetcode.com/problems/word-break/

A

Top down approach with memorization:

// Check if the prefix exists in the dictionary and recursively check if the rest of the string is valid —which means it can be broken into words which exists in the dictionary.

for(int end = start + 1; end <= s.length(); end++) {
if(wordDict.contains(s.substring(start, end)) && wordBreakHelper(s, wordDict, end, memo)) {
return memo[start] = true;
}
}

Bottom up approach

  1. Check if every substring(0,i) can be broken down into valid strings.
 for(int i = 1; i <= s.length(); i++) {
            for(int j = 0; j < i; j++) {
                if(dp[j] && wordDict.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }    
            }
        }
49
Q

House Robber

https://leetcode.com/problems/house-robber/

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

A

TBD

50
Q
  1. Serialize and Deserialize Binary Tree
    https: //leetcode.com/problems/serialize-and-deserialize-binary-tree/

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

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

A
serialize{
   StringBuilder sb  = new StringBuilder();

levelOrder();

return sb.deleteCharacterAt(sb.length() - 1).toString();
}

private void levelorder(TreeNode root, StringBuilder sb) {
if(root == null)
return;

Queue queue = new LinkedList<>();

queue.add(root);

while(!queue.isEmpty()) {
TreeNode element = queue.poll();

  if(element == null) {
   sb.append("null",);
 } else {
   sb.append(element.left + ",");
   sb.append(element.right + ",");
}
}
}

deserialize() {

}

51
Q

Jump Game

https://leetcode.com/problems/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.

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

A

Backtracking/Recursion

private boolean backtrack(int[] nums, position) {
        // Base case
        if(position == nums.length - 1)
          return true;
    int maxPossibleJumpLength = Math.min(position + nums[position], nums.length - 1);
        for(int i = position + 1; i <= maxPossibleJumpLength; i++) {
            if(backtrack(nums, i))
                return true;
        }
        return false;
  }  

Topdown approach with Memoization

private boolean backtrack(int[] nums, int position, Boolean[] memo) {
    // Base case
    if(position == nums.length - 1)
        return memo[position];
if(memo[position] != null)
    return memo[position];

    int maxPossibleJumpLength = Math.min(position + nums[position], nums.length - 1);

    for(int i = position + 1; i <= maxPossibleJumpLength; i++) {
        if(backtrack(nums, i, memo)) {
            memo[position] = true;
            return memo[position]; 
        }
    }

    memo[position] = false;
    return memo[position];   } 

Bottom-up Dynamic Programming:

    for(int i = numsLength - 2; i >= 0; i--) {
        int end = Math.min(i + nums[i], numsLength - 1);
        for(int j = i + 1; j <= end; j++) {
            if(dp[j]) {
                dp[i] = true;
                break;
            }
        }
    }
52
Q

Jump Game ||

A

int jumps = 0, currentEnd = 0, farthest = 0(farthest possible jump);

        for(int i = 0; i < nums.length - 1; i++) {
            // Update the farthest jump which could have been possible.
            farthest = Math.max(farthest, i + nums[i]);
            if(i == currentEnd) {
                jumps++;
                currentEnd = farthest;
            }
        }

return jumps;

https://www.youtube.com/watch?v=cfdwhSmLt3w&ab_channel=CodeforCause

53
Q
  1. House Robber
    https: //leetcode.com/problems/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.

A

Dynamic Programming:

maxRobbedAmount[i] = Math.max(maxRobbedAmount[i + 1], maxRobbedAmount[i + 2] + nums[i]);

Optimized Dynamic Programming

for(int i = numsLength - 2; i >=0; i–) {
answer = Math.max(nums[i] + nextNextHouse, nextHouse);
nextNextHouse = nextHouse;
nextHouse = answer;

}

54
Q

House Robber II

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system 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.

A

int value1 = House Robber 1 with first house excluded;
int value2 = House Robber1 with last house excluded;

return Math.max(value1, value2);

55
Q

Unique Paths

https://leetcode.com/problems/unique-paths/

A

for(int[] each: nums)
Arrays.fill(each, 1);

        for(int i = 1; i < m; i++) {
            for(int j = 1; j < n; j++) {
                nums[i][j] = nums[i-1][j] + nums[i][j-1];
            }
        }
    return nums[m-1][n-1];
56
Q
  1. Unique Paths
A
for(int i = 1; i < m; i++) {
            for(int j = 1; j < n; j++) {
                nums[i][j] = nums[i-1][j] + nums[i][j-1];
            }
        }
57
Q
  1. Subtree of Another Tree

https: //leetcode.com/problems/subtree-of-another-tree/

A

public boolean isSubtree(TreeNode s, TreeNode t) {
if(s == null)
return false;

        return compareTrees(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t);
    }
58
Q

Validate Binary Search Tree

https://leetcode.com/problems/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.

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

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.

A
  1. Perform inorder traversal
  2. Keep a track of the previous element
  3. if the current element in the traversal is <= the previous element, then return false;

int leftDecision = inorder(root.left);

if(prev != null && prev.val >= root.val)
return false;

int rightDecision = inorder(root.right);

return leftDecision && rightDecision;

59
Q
  1. Construct Binary Tree from Preorder and Inorder Traversal
    https: //leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
A

Prerequisites:

// Determine the index of the root
int rootValue = preorder[preOrderIndex++];
int rootIndex = indices.get(rootValue);
TreeNode root = new TreeNode(rootValue);

root. left = recurse(left, rootIndex - 1, indices);
root. right = recurse(rootIndex + 1, right, indices);

return root;

60
Q
  1. Kth Smallest Element in a BST
    https: //leetcode.com/problems/kth-smallest-element-in-a-bst/

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

A
  1. Inorder traversal of the tree.
  2. Store the elements in a list
  3. Return the Kth smallest element of the list.
61
Q
  1. Lowest Common Ancestor of a Binary Search Tree

https: //leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

A

private boolean recurseTree(TreeNode root, TreeNode p, TreeNode q) {
if(root == null)
return false;

        // Recursively search for p and q in the left sub-tree.
        int leftSubtreeDecision = recurseTree(root.left, p, q) ? 1: 0;
        // Recursively search for p and q in the right sub-tree.
        int rightSubtreeDecision = recurseTree(root.right, p, q) ? 1: 0;
        // If root is either p or q 
        int rootDecision = (root == p) || (root == q) ? 1 : 0;
    if(leftSubtreeDecision + rightSubtreeDecision + rootDecision >= 2)
        this.result = root;

    // Return true if atleast one of the values leftSubtreeDecision, rightSubtreeDecision, rootDecision is true.

    return leftSubtreeDecision + rightSubtreeDecision + rootDecision > 0;
}
62
Q
  1. Implement Trie (Prefix Tree)

https: //leetcode.com/problems/implement-trie-prefix-tree/

A
class TrieNode {
    private static int R = 26;
TrieNode[] links;

private boolean isEnd; }

Trie {

void insert(String word)

boolean search(String word)

// Searches for the prefix, returns the node if it exists, null otherwise
private TrieNode searchPrefix(String prefix) 
// Calls the searchPrefix method, if the method returns a non-null node which isn't the end node, then returns true, false otherwise.
boolean startsWith(String prefix)
}
63
Q
  1. Design Add and Search Words Data Structure

https: //leetcode.com/problems/design-add-and-search-words-data-structure/

A

// Build the Trie. The links can either be stored in a HashMap or an Array.

    class TrieNode {
        Map children = new HashMap<>();
        boolean word = false;
        public TrieNode() {}
    }
public boolean search(String word) {
        return helper(word, trie);
    }
private boolean helper(String word, TrieNode node) {
    for(int i = 0; i < word.length(); i++) {
        char ch = word.charAt(i);
        if(!node.children.containsKey(ch)) {
            if(ch == '.') {
                for(Character key: node.children.keySet()) {
                    if(helper(word.substring(i + 1), node.children.get(key)))
                        return true;
                } 
            }
            return false;
        } else {
            node = node.children.get(ch);
        }
    }

    return node.word;
}
64
Q
  1. Word Search II

https: //leetcode.com/problems/word-search-ii/

A
private void backtracking(int row, int col, TrieNode parent) {
// Get the current node
Character letter = this.board[row][col];
TrieNode currNode = parent.children.get(letter);
// Check if the word formed based on the current path explored exists in the Trie. 
if(currNode.word != null) {
// Add the word to the output list.
this.result.add(word);
// Mark the word as visited.
currNode.word =  null;
}
// Mark the letter as visited
this.board[row][col]  = '#';
// Explore all four directions.
int[] rowOffset = [-1, 0, 1, 0];
int[] colOffset = [0, -1, 0, 1];

for(int i = 0; i < 4; i++) {
int newRow = row + rowOffset[i];
int newColumn = col + colOffset[i];

  // Continue if either newRow  or newColumn is out of bounds.
if(newRow < 0 || newRow >= this.board.length || newCol < 0 || newCol >= this.board[0].length)
continue;

if(currNode.children.containsKey(this.board[newRow][newCol])) {
backtracking(newRow, newCol, currNode);
}

this.board[row][col] = letter;
}
}

65
Q
  1. Top K Frequent Elements

https: //leetcode.com/problems/top-k-frequent-elements/

A
  1. Build the num -> frequency map.
  2. Store at most K elements in a min heap with the least frequent element at the top of the heap.

Queue maxHeap = new PriorityQueue((n1, n2) -> map.get(n1) - map.get(n2));

  1. Return the K elements in decreasing order of frequency.
66
Q
  1. Find Median from Data Stream

https: //leetcode.com/problems/find-median-from-data-stream/

A

[[], [1], [2], [], [3], []]

minHeap -> Contains the smaller half of the elements.
maxHeap -> Contains the largest half of the elements.

public void addNum(int num) {
maxHeap.add(num);
balanceHeaps();
}

balanceHeaps() {
minHeap.add(maxHeap.poll());

If(minHeap.size() > maxHeap.size()) {
maxHeap.add(minHead.poll())
}

findMedian() {
if(maxHeap.size() > minHeap.size())
  return maxHeap.peek();
else
  return ((double) maxHeap.peek() + minHeap.peek())*0.5;
}
}
67
Q
  1. Best Time to Buy and Sell Stock
    https: //leetcode.com/problems/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.

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.

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

A

for (int i = 0; i < pricesLength; i++) {
if(minPrice > prices[i]) {
minPrice = prices[i];
} else if(prices[i] - minPrice > maxProfit){
maxProfit = prices[i] - minPrice;
}
}

68
Q
  1. Contains Duplicate

https: //leetcode.com/problems/contains-duplicate/

A

Store in a set.

69
Q
  1. Product of Array Except Self

https: //leetcode.com/problems/product-of-array-except-self/

A
  1. Build the leftProductArray
  2. Build the rightProductArray

result[i] = leftProductArray[i - 1] * rightProductArray[i + 1]

70
Q
  1. 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.

It is guaranteed that the answer will fit in a 32-bit integer.

A subarray is a contiguous subsequence of the array.

https://leetcode.com/problems/maximum-product-subarray/

Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

A
  1. Compute the maxSoFar -> Indicates the maximum subarray product up to a point.

int tempMax = Math.max(curr, Math.max(currmaxSoFar, currminSoFar));

  1. Compute the minSoFar -> Indicates the minimum subarray product up to a point.

minSoFar = Math.min(curr, Math.min(currmaxSoFar, currminSoFar));

result = Math.max(result, maxSoFar);

71
Q
  1. 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.

https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/

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

A

Binary Search in the array:

        // case when the minimum element is found.
        if(mid > 0 && nums[mid - 1] > nums[mid])
            return nums[mid];
        else if(nums[mid] < nums[0])
            return binarySearch(nums, start, mid - 1);
        else
            return binarySearch(nums, mid + 1, end);
72
Q
  1. Merge Intervals

https: //leetcode.com/problems/merge-intervals/

A
  1. Sort the intervals on the start time
  2. If the output list is either empty or if the current interval is non-overlapping with the last interval in the output array/list, then add the current interval to the output list.
  3. If the intervals are overlapping, then merge them and add the merged interval to the output list.
                // Merge the element and add to the output list. 
                int[] temp = new int[2];
            temp[1] = Math.max(output.getLast()[1], interval[1]);
            temp[0] = Math.min(output.getLast()[0], interval[0]);

            output. removeLast();
            output. add(temp);
73
Q
  1. Non-overlapping Intervals

https: //leetcode.com/problems/non-overlapping-intervals/

A
  1. Sort the intervals based on the end time.
  2. Prev = intervals[0]; curr = intervals[i] where i runs from 1 through N.
  3. If curr overlaps with the previous interval, then skip/remove the current interval. Update the removed interval count.
  4. if the curr interval doesn’t overlap with the previous interval, then include teh current interval in the output; previous become the current.

Return the removed interval count.

74
Q
  1. Meeting Rooms

https: //leetcode.com/problems/meeting-rooms/

A
  1. Sort the intervals by start time

2. If there is atleast one overalap then return false or else return true.

75
Q
  1. Meeting Rooms II

https: //leetcode.com/problems/meeting-rooms-ii/

A

TBD

76
Q

Justify Text

https://leetcode.com/problems/text-justification/

A

int right = findRight(left, words, maxWidth);
result.add(justifyText(left, right, words, maxWidth));

    private String justifyText(int left, int right, String[] words, int maxWidth) {  
        // If only one word left to be processed
        if(left - right == 0) return padResult(words[left], maxWidth);
    int numSpaces = right - left;
    int totalSpace = maxWidth - wordsLength(words, left, right);
    boolean isLastLine = right == words.length - 1;

    String space = isLastLine ? " ": blank(totalSpace/numSpaces);
    int remainder = isLastLine ? 0 : totalSpace % numSpaces; 

    StringBuilder result = new StringBuilder();       
    // Build a line with one space inserted between the words
    for(int i = left; i <= right; i++) {
        result.append(words[i]);
        result.append(space);
        result.append(remainder-- > 0 ? " ": "");
    }
        return padResult(result.toString().trim(), maxWidth);
    }
77
Q

https://leetcode.com/problems/basic-calculator/

A

TBD

78
Q

https://leetcode.com/problems/word-ladder/

A

TBD

79
Q

https://leetcode.com/problems/word-ladder-ii/

A

TBD

80
Q

https://leetcode.com/problems/target-sum/

A

TBD