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.

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;

    }
}

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