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.

String to Integer (atoi) - LeetCode

Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
Example 1:
Input: "42"
Output: 42
Example 2:
Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.
Java Solution :
class Solution {
    public int myAtoi(String str) {
      if(str == null || str.isEmpty())
          return 0;
        int sign =1, i =0, n = str.length();
        while(i < n && str.charAt(i) == ' ')
            ++i;
        if(i >= n)
            return 0;
        if(str.charAt(i) == '+' || str.charAt(i) == '-')
            sign = str.charAt(i++) == '+' ? 1 : -1;
        long res = 0;
        while( i<n && Character.isDigit(str.charAt(i))){
            res = res * 10 + (str.charAt(i++) - '0');
            if(res * sign > Integer.MAX_VALUE || res * sign < Integer.MIN_VALUE)
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        return (int) (res * sign);
    }
}

Reorder Log Files - LeetCode

You have an array of logs.  Each log is a space delimited string of words.
For each log, the first word in each log is an alphanumeric identifier.  Then, either:
  • Each word after the identifier will consist only of lowercase letters, or;
  • Each word after the identifier will consist only of digits.
We will call these two varieties of logs letter-logs and digit-logs.  It is guaranteed that each log has at least one word after its identifier.
Reorder the logs so that all of the letter-logs come before any digit-log.  The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties.  The digit-logs should be put in their original order.
Return the final order of the logs.

Example 1:
Input: ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
Java Solution :
class Solution {
    public String[] reorderLogFiles(String[] logs) {
      Arrays.sort(logs, (log1, log2) -> {
            String[] split1 = log1.split(" ", 2);
            String[] split2 = log2.split(" ", 2);
            boolean isDigit1 = Character.isDigit(split1[1].charAt(0));
            boolean isDigit2 = Character.isDigit(split2[1].charAt(0));
            if (!isDigit1 && !isDigit2) {
                int cmp = split1[1].compareTo(split2[1]);
                if (cmp != 0) return cmp;
                return split1[0].compareTo(split2[0]);
            }
            return isDigit1 ? (isDigit2 ? 0 : 1) : -1;
        });
        return logs;
    } 
}

Group Anagrams - LeetCode

Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Note:
  • All inputs will be in lowercase.
  • The order of your output does not matter.

Java Solution :
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> groupedAnagrams = new ArrayList<>();
        Map<String , List<String>> map = new HashMap<>();
        for(String str : strs){
            char [] strchars = str.toCharArray();
            Arrays.sort(strchars);
            String sorted = new String(strchars);
            if(!map.containsKey(sorted))
                map.put(sorted,new ArrayList<>());
            map.get(sorted).add(str);
        }
        groupedAnagrams.addAll(map.values());
            return groupedAnagrams;

    }
}

Reverse a linked list - LeetCode

Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?

Java Solution : Iterative Method (Three pointer approach)
prev , current , next
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null)
            return null;
        ListNode current = head;
        ListNode prev = null;
        ListNode next = null;
        
        while(current !=null){
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        head = prev;
        return head;
        
    }
}

Jump Game - LeetCode

Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.

Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.
Java Solution :
class Solution {
    public boolean canJump(int[] nums) {
        if(nums.length <=1)
            return true;
        int jumpValue = nums[0];
        for(int i =0 ; i < nums.length; i++){
            if(jumpValue <= i && nums[i]==0) //Condition to check if can't move futher
                return false;
            if(i + nums[i] > jumpValue) //Value to jump from current postion
                jumpValue = nums[i]+i;
            if(jumpValue >= nums.length-1) //if we reach last index or beyond that we acheived.
                return true;
        }
        return false;
    }
}

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