LeetCode - Meeting Rooms II

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
Java Solution :
class Solution {
    public int minMeetingRooms(int[][] intervals) {
        Arrays.sort(intervals,(a,b)-> a[0] - b[0]);
        int numOfMeetingRooms = 0;
PriorityQueue<Integer> minHeap = new PriorityQueue<>();        
        for(int[] interval : intervals){
            if(minHeap.isEmpty()){
                minHeap.offer(interval[1]);
                numOfMeetingRooms++;
            }else if(minHeap.peek() <= interval[0]){
                minHeap.poll();
                minHeap.offer(interval[1]);
            }else{
                minHeap.offer(interval[1]);
                numOfMeetingRooms++;
            }
        }
       return numOfMeetingRooms;
    }
}

LeetCode - Merge K Sorted Lists

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 result = dummy;
            while(!minHeap.isEmpty()){
                result.next = new ListNode(minHeap.remove());
                result = result.next;
            }
            return dummy.next;
    }
}

LeetCode - Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count 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.
Example 1:
Input:
11110
11010
11000
00000

Output: 1
Example 2:
Input:
11000
11000
00100
00011

Output: 3
Java Solution ;
class Solution {
    public int numIslands(char[][] grid) {
        int numOfIslands = 0;
        for(int i =0; i < grid.length;i++){
            for(int j=0; j < grid[i].length;j++){
                if(grid[i][j] == '1')
                numOfIslands += dfs(grid,i,j);
            }
        }
        return numOfIslands;
    }
    public int dfs (char[][] grid , int i , int j){
        if(i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] == '0'){
            return 0;
        }
        
        grid[i][j] = '0';
        dfs(grid,i+1,j);
        dfs(grid,i-1,j);
        dfs(grid,i,j+1);
        dfs(grid,i,j-1);
        return 1;
    }
}

LeetCode - Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Java Solution:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode temp = new ListNode(0);
        int carry = 0;
        ListNode headA =l1 , headB = l2 , curr = temp;
     
           while (headA != null || headB !=null){
                int x = (headA != null) ? headA.val : 0;
                int y = (headB != null) ? headB.val : 0;
                int sum = x + y + carry;
                carry = sum / 10;
                curr.next = new ListNode(sum % 10);     
                curr = curr.next;
               if(headA != null) headA = headA.next;
               if(headB != null) headB = headB.next;
           }
            if(carry > 0)
                curr.next = new ListNode(carry);
            return temp.next;
        
    }
}
Time Complexity : O(max(m,n))
Space Complexity : O(max(m,n))+1

LeetCode - Valid Parentheses

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<Character>();
        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();
    }
}

LeetCode - Most Common Word

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words.  It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation.  Words in the paragraph are not case sensitive.  The answer is in lowercase.

Example:
Input: 
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"
Explanation: 
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. 
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"), 
and that "hit" isn't the answer even though it occurs more because it is banned.

Note:
  • 1 <= paragraph.length <= 1000.
  • 0 <= banned.length <= 100.
  • 1 <= banned[i].length <= 10.
  • The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)
  • paragraph only consists of letters, spaces, or the punctuation symbols !?',;.
  • There are no hyphens or hyphenated words.
  • Words only consist of letters, never apostrophes or other punctuation symbols.
Java Solution:

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        String result =" ";
        Set<String> bannedset = new HashSet<String>();
        for(String word : banned) bannedset.add(word);
        Map<String,Integer> map = new HashMap<String,Integer>();
        String[] parawords = paragraph.replaceAll("[^a-zA-Z]"," ").toLowerCase().split(" ");
        for(String pword : parawords){
            if(!bannedset.contains(pword) && !pword.isEmpty())
                map.put(pword,map.getOrDefault(pword,0)+1);
        }
        
        int max =0;
        for(String word1 : map.keySet()){
            if(map.get(word1)>max){
                max = map.get(word1);
                result = word1;
            }
        }
        return result;
    }
}

LeetCode - Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Java Solution :
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0; i< nums.length;i++){
            int complement = target-nums[i];
            if(map.containsKey(complement)){
                return new int[] { map.get(complement),i};
            }
            map.put(nums[i],i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}
Time complexity : O(n) Space Complexity O(n)

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