Merge Two Sorted Lists - LeetCode

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Java Solution :
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode node = new ListNode(-1);
        ListNode head = node;
        while(l1 != null && l2 !=null){
            if(l1.val < l2.val){
                node.next = l1;
                l1 = l1.next;
            }else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        
        if(l1 !=null){
            node.next = l1;
        }else if(l2 != null){
            node.next = l2;
        }
        
        return head.next;
        
    }
}

Merge k Sorted Lists - LeetCode

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6
Java Solution : 
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        
        for(ListNode head : lists){
            while(head != null){
                minHeap.add(head.val);
                head = head.next;
            }
        }
        
        ListNode dummy = new ListNode(-1);
        ListNode head = dummy;
        
        while(!minHeap.isEmpty()){
            head.next = new ListNode(minHeap.remove());
            head = head.next;
        }
        return dummy.next;
    }
}

Valid Parentheses - LeetCode

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.
An input string is valid if:
  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
Java Solution:
class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        
        for(char c : s.toCharArray()){
            if(c == '[' || c == '{' || c == '('){
                stack.push(c);
            }else if(c == ']' && !stack.isEmpty() && stack.peek() == '['){
                stack.pop();
            }else if(c == '}' && !stack.isEmpty() && stack.peek() == '{'){
                stack.pop();
            }else if(c == ')' && !stack.isEmpty() && stack.peek() == '('){
                stack.pop();
            }else{
                return false;
            }           
        }
        return stack.isEmpty();
    }
}

Maximum Subarray - LeetCode

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Java Solution :
class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length == 0)
            return 0;
        int prev = nums[0];
        int maxValue = nums[0];
        for(int i =1; i < nums.length ; i++){
            prev = prev > 0 ? prev+nums[i] : nums[i];
            if(maxValue < prev)
                maxValue = prev;
        }
        return maxValue;
    }
}

Coin Change - LeetCode

You are given coins of different denominations and a total amount of money amount. Write a function to compute 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.
Example 1:
Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.
Java Solution:
class Solution {
    public int coinChange(int[] coins, int amount) {
        Arrays.sort(coins);
        int [] dp = new int[amount+1];
        Arrays.fill(dp,amount+1);
        dp[0] = 0;
        for(int i = 0; i <= amount; i++){
            for(int j = 0; j < coins.length ; j++){
                if(coins[j]<=i)
                dp[i] = Math.min(dp[i], 1+dp[i-coins[j]]);
                else
                    break;
            }
        }
        return dp[amount] > amount ? -1:dp[amount] ;
    }
}


Missing Number - LeetCode

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
Java Solution :
class Solution {
    public int missingNumber(int[] nums) {
        if(nums == null || nums.length < 1)
            return 0;
        Arrays.sort(nums);
        int n = nums[nums.length-1];
        int sum = (n*(n+1))/2;
        int result = 0;
        for(int i=0;i<nums.length;i++)
            result+=nums[i];
        if(result == sum && nums[0]==0)
            return nums[nums.length-1]+1;
        return sum-result;
    }
}

Container With Most Water - Leet Code

Given n non-negative integers a1a2, ..., a, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
Java Solution :
class Solution {
    public int maxArea(int[] height) {
        int max = Integer.MIN_VALUE;
        int i =0;
        int j = height.length-1;
        while(i<j){
            int min = Math.min(height[i],height[j]);
            max = Math.max(max, (j-i)*min);
            if(height[i]<height[j]){
                i++;
            }else {
                j--;
            }
        }
        return max;
    }
}
Complexity Analysis
  • Time complexity : O(n). Single pass.
  • Space complexity : O(1). Constant space is used.

Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...