Bea.AI coding blog
  • Tree
    • Tree Traverse
    • Iteration based traverse
    • Typical problems and solutions
      • Max width of binary tree
      • Binary Tree & BST Serialize & Deserialize
      • Lowest common ancestor (LCA) for Binary Tree and BST
      • Subproblem-based Approach for Resolving Max Value on Trees
      • Path sum III
  • Graph
  • Data structure
    • Java data structure
  • Algorithm general templates
    • Tree
    • Trie
    • Graph
  • Java Algorithm Tips and Tricks
    • Java concurrent list
  • Coding patterns & Strategies
  • Coding patterns & template
    • 1. Binary Search
    • 2. Two Pointer
    • 3. Sliding Window
    • 4. Backtracking
    • 5. DFS
    • 6. BFS
    • 7. Stack
    • 8. Heap
    • 9. Prefix Sum
    • 10. Linked List
    • 11. BST
    • 12. Line sweep
    • 14. Tree
    • 15. Graph
    • 16. Bit manipulation
    • 17. Matrix
    • 18. Monotonic Stack
    • 19. Sorting
    • 20. Union Find
    • 21. Trie
    • 22. Dynamic programming
    • 23. Customized Data Structure
  • Code interview steps
  • Leetcode
    • Tree
      • Traversal
      • Construction and Conversion
      • Search and Validation
      • Manipulation and Modification
      • Special Trees
      • Miscellaneous
    • Dynamic programing
      • Classic DP Problems
      • Sequence/Array DP
      • Matrix DP
      • Knapsack Problems
      • String DP
      • Tree/Graph DP
      • Optimization Problems
      • Combinatorial DP
    • DFS
      • Graph Traversal
      • Path Finding
      • Tree Traversal
      • Backtracking
      • Topological Sorting
      • Traversal Order
      • Dynamic Programming with DFS
      • Connected Components
    • BFS
      • Graph
      • Tree
      • Matrix
      • String
      • Others
    • Two points
      • Array
      • String
      • Linked List
      • Sorting
      • Others
    • LinkedList
      • Basic Operations
      • Cycle Detection and Handling
      • Intersection and Union
      • Partitioning and Merging
      • Palindrome
      • Miscellaneous
    • Backtracking
    • Binary Search
    • Union Find
    • Trie
    • Sort
    • Heap
    • Randomness
    • Topological sort
    • Stack
    • HashTable
    • Sliding Window
  • Blind 75
    • Array
    • Binary
    • Dynamic Programming
    • Graph
    • Interval
    • LinkedList
    • Matrix
    • String
    • Tree
    • Heap
  • Companies
    • Apple
Powered by GitBook
On this page
  • 1. Container With Most Water
  • 2. Three Sum
  • 3. Trapping Rain Water
  • 4. Remove Duplicates from Sorted Array
  • 5. Merge Sorted Array
  1. Leetcode
  2. Two points

Array

PreviousTwo pointsNextString

Last updated 1 year ago

1. Container With Most Water

  1. Problem Description:

The problem "Container With Most Water" on LeetCode asks us to find the maximum area of water that can be trapped between two vertical lines in a given array of non-negative integers. Each element in the array represents the height of a line at that position, and the width between any two lines is always 1.

Link to the problem:

  1. Java Solution:

Here is the optimized Java code for the "Container With Most Water" problem on LeetCode:

public class ContainerWithMostWater {
    public int maxArea(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int maxArea = 0;

        while (left < right) {
            int currentArea = Math.min(height[left], height[right]) * (right - left);
            maxArea = Math.max(maxArea, currentArea);

            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }

        return maxArea;
    }
}
  1. Algorithm Explanation:

We can solve this problem using a two-pointer approach. We initialize two pointers, one at the beginning of the array (left) and the other at the end of the array (right). The maximum area can be calculated as the minimum of the heights at these two pointers multiplied by the difference between the two pointers.

We start by calculating the area between the lines at left and right and store it as maxArea. Then we move the pointer pointing to the smaller line (either left or right) one step closer to the other pointer. We repeat this process until left and right meet.

By moving the smaller pointer, we are able to explore different pairings of lines and find the maximum area. This is because moving the bigger pointer towards the smaller pointer won't increase the area and only moving the smaller pointer has a chance to give a larger area.

During the interview process, it is important to clearly explain the two-pointer approach and the reasoning behind why moving the smaller pointer is more likely to increase the area. Additionally, it is beneficial to discuss the time complexity of the solution, which is O(n), where n is the length of the input array height.

2. Three Sum

  1. Problem Description: The problem "Three Sum" on LeetCode asks us to find all unique triplets in the given array that add up to zero. We need to return a list of triplets, where each triplet contains three numbers, and the sum of those three numbers equals zero. The array can contain duplicate numbers, and the solution must not contain duplicate triplets.

  1. Optimized Java Code for "Three Sum" problem:

import java.util.*;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        
        if (nums == null || nums.length < 3) {
            return result;
        }
        
        Arrays.sort(nums);
        
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            
            int target = -nums[i];
            int left = i + 1;
            int right = nums.length - 1;
            
            while (left < right) {
                int sum = nums[left] + nums[right];
                
                if (sum == target) {
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    left++;
                    right--;
                    
                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    
                    while (left < right && nums[right] == nums[right + 1]) {
                        right--;
                    }
                } else if (sum < target) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        
        return result;
    }
}
  1. Detailed Description and Approach:

In this problem, we need to find triplets in the given array that add up to zero. To solve this problem efficiently, we can use the Two Pointers approach along with sorting the array.

The algorithm follows these steps:

  • Sort the given array in ascending order. This allows us to use two pointers - one starting from the leftmost element (left) and the other starting from the rightmost element (right).

  • Iterate over the sorted array from left to right. For each element, set it as the potential triplet's first element (nums[i]).

  • Set the target value as the negated value of the first element (-nums[i]).

  • Initialize left as i + 1 and right as the index of the last element in the array.

  • While left < right, compare the sum of nums[left] and nums[right] with the target value.

  • If the sum is equal to the target value, add the triplet (nums[i], nums[left], nums[right]) to the result list.

  • Increment left and decrement right to find the next possible pair and avoid duplicates.

  • Continue this process while moving the pointers left and right towards each other.

  • If the sum is less than the target value, increment left to increase the sum.

  • If the sum is greater than the target value, decrement right to decrease the sum.

  • Skip any duplicate values to avoid duplicate triplets and move the pointers accordingly.

  • Return the result list containing all unique triplets.

By using the Two Pointers approach and sorting the array, we can find all unique triplets that add up to zero in O(n^2) time complexity, where 'n' is the length of the input array.

3. Trapping Rain Water

  1. Problem Description and Leetcode Link: The problem is called "Trapping Rain Water" and the Leetcode link is: https://leetcode.com/problems/trapping-rain-water/

  2. Optimized Java code for "Trapping Rain Water": Here is the optimized Java code with detailed comments:

public class Solution {
    public int trap(int[] height) {
        int left = 0; // pointer for the left wall
        int right = height.length - 1; // pointer for the right wall
        int leftMax = 0; // current max height from left side
        int rightMax = 0; // current max height from right side
        int trappedWater = 0; // total trapped water
        
        while (left < right) {
            if (height[left] < height[right]) {
                // current left height is smaller than right height
                
                if (height[left] >= leftMax) {
                    // update the left max height
                    leftMax = height[left];
                } else {
                    // trap water at the current position
                    trappedWater += leftMax - height[left];
                }
                
                left++; // move the left pointer to the next position
            } else {
                // current right height is smaller than left height
                
                if (height[right] >= rightMax) {
                    // update the right max height
                    rightMax = height[right];
                } else {
                    // trap water at the current position
                    trappedWater += rightMax - height[right];
                }
                
                right--; // move the right pointer to the next position
            }
        }
        
        return trappedWater;
    }
}
  1. Detailed Description of the Algorithm and Interview Process: In this problem, we need to calculate the amount of water that can be trapped between the walls given an array representing the heights of the walls.

The optimized solution for this problem is based on the two-pointer approach. We use two pointers, one starting from the left (left) and the other starting from the right (right), to track the heights of the walls. We also maintain two variables, leftMax and rightMax, to keep track of the maximum height encountered so far from the left and right sides.

We iterate over the array using these pointers until they meet. At each iteration, we compare the heights at the left and right positions. If the height at the left position is smaller, we update the leftMax if necessary and calculate the trapped water between the current position and the leftMax. Similarly, if the height at the right position is smaller, we update the rightMax if necessary and calculate the trapped water between the current position and the rightMax.

After the iteration, we would have calculated the total trapped water, which we return as the result.

During an interview process, it is important to first understand the problem statement clearly. Then, start by explaining the intuitive approach to solve the problem. In this case, we can think of using the two-pointer approach to track the heights from the left and right sides and calculate the trapped water.

Next, write the code for the solution, ensuring to add detailed comments to explain the logic behind each step. It is important to handle edge cases and discuss the time and space complexities of the solution. Finally, test the code with different test cases to validate its correctness.

By understanding the problem, explaining the approach, and providing an optimized solution with detailed comments, you can showcase your problem-solving skills during an interview process.

4. Remove Duplicates from Sorted Array

  1. Problem Description: The problem is to remove the duplicates in-place from a sorted array. We need to modify the array in such a way that each element appears only once and returns the new length of the modified array. It is not necessary to maintain the order of the elements beyond the new length.

Link to the problem: https://leetcode.com/problems/remove-duplicates-from-sorted-array/

  1. Optimized Java Code:

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        
        int i = 0;
        for (int j = 1; j < nums.length; j++) {
            if (nums[j] != nums[i]) {
                i++;
                nums[i] = nums[j];
            }
        }
        return i + 1;
    }
}
  1. Algorithm Explanation and Interview Tips:

  • The problem statement mentions that the given array is already sorted. This provides a hint that we can solve the problem efficiently by using a two-pointer technique.

  • We can have two pointers, i and j, where i represents the position to insert the unique element and j represents the position at which the next element is checked for duplicacy.

  • Initially, we start with i=0 and j=1. As we iterate through the array, we compare the elements at positions i and j. If they are equal, it means we have encountered a duplicate. In this case, we increment j to move to the next element.

  • If the elements at positions i and j are not equal, it means we have found a unique element. We increment i and update the value at position i with the value at position j. This step effectively removes the duplicate element by overwriting it with the next unique element.

  • By doing this, we maintain a subarray [0, i] that contains only unique elements. The variable i represents the length of this subarray.

  • Finally, we return i + 1 as the answer, which represents the length of the modified array.

During an interview, the interviewer may ask you to explain the algorithm in detail and possibly optimize the solution further. You can discuss the time complexity, which is O(n), where n is the number of elements in the given array. This solution avoids unnecessary copying of elements by overwriting duplicates in-place, resulting in an optimized solution.

5. Merge Sorted Array

  1. Problem description and link:

    • Problem: Merge Sorted Array

    • Link: https://leetcode.com/problems/merge-sorted-array/

  2. Java code for the problem "Merge Sorted Array" with detailed comments:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        // Initialize two pointers:
        int i = m - 1; // Pointer for the last element in nums1
        int j = n - 1; // Pointer for the last element in nums2
        int k = m + n - 1; // Pointer for the last vacant position in nums1
        
        // Merge nums1 and nums2 from the end of the arrays
        while (i >= 0 && j >= 0) {
            // Compare the last elements of nums1 and nums2
            // Place the larger element at the last vacant position in nums1 and move the pointers accordingly
            if (nums1[i] > nums2[j]) {
                nums1[k] = nums1[i];
                i--;
            } else {
                nums1[k] = nums2[j];
                j--;
            }
            k--;
        }
        
        // If there are remaining elements in nums2, merge them to nums1
        while (j >= 0) {
            nums1[k] = nums2[j];
            k--;
            j--;
        }
    }
}
  1. Detailed description and algorithm walkthrough:

    • The problem requires merging two sorted arrays (nums1 and nums2) in-place, where nums1 has enough space to hold all elements.

    • To solve this problem, we need to ensure that the merged array (nums1) is sorted.

    • We can start merging from the end of the arrays as nums1 has enough vacant space at the end.

    • Initialize three pointers: i to the last element of nums1, j to the last element of nums2, and k to the last vacant position in nums1.

    • We iterate until i and j are greater than or equal to 0.

    • At each iteration, we compare the last elements of nums1 and nums2.

    • The larger element is placed at the last vacant position in nums1, and the corresponding pointer (i or j) is moved backward.

    • The pointer k is also moved backward to the position of the next vacant position in nums1.

    • After the above loop, if there are any remaining elements in nums2, we can simply merge them into nums1 starting from the end.

    • Finally, we have successfully merged nums1 and nums2 in-place, resulting in a sorted nums1 array.

During an interview process, it is important to clearly understand the problem statement and constraints. Then, come up with an optimized approach to solve the problem. In this case, merging from the end of the arrays helps eliminate the need for shifting elements in nums1, resulting in an efficient solution with a time complexity of O(m + n) and constant space complexity.

To improve your problem-solving skills during an interview, it is beneficial to understand common algorithms and data structures, practice implementing them, and be able to analyze time and space complexities. Regularly participating in coding challenges, like LeetCode, helps improve problem-solving skills and familiarity with different types of problems.

Problem Link:

Container With Most Water
Three Sum