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)

LeetCode-Merge Two Sorted Lists

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
Iterative Approach :
/**
 * 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 preNode = new ListNode(-1);
        ListNode prev = preNode;
        
        while (l1!=null && l2!=null){
            if(l1.val <= l2.val){
                prev.next = l1;
                l1 = l1.next;
            }else{
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }
        prev.next = l1 == null ? l2 : l1;
        return preNode.next;
    }
}
Time Complexity : O(n+m) Space Complexity O(1)
Recursive Approach:
/**
 * 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) {
        if(l1 == null){
            return l2;
        }else if(l2 == null){
            return l1;
        }else if(l1.val <l2.val){
                l1.next = mergeTwoLists(l1.next,l2);
            return l1;
            }else{
                l2.next = mergeTwoLists(l1,l2.next);
            return l2;
            }
        }
}
Time Complexity : O(n+m) Space Complexity : O(n+m)

LeetCode - Two Sum Less Than K

Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this equation, return -1.

Example 1:
Input: A = [34,23,1,24,75,33,54,8], K = 60
Output: 58
Explanation: 
We can use 34 and 24 to sum 58 which is less than 60.
Example 2:
Input: A = [10,20,30], K = 15
Output: -1
Explanation: 
In this case it's not possible to get a pair sum less that 15.

Note:
  1. 1 <= A.length <= 100
  2. 1 <= A[i] <= 1000
  3. 1 <= K <= 2000
Java Solution ;

class Solution {
    public int twoSumLessThanK(int[] A, int K) {
        Arrays.sort(A);
        int maxSum = -1;
        int i = 0;
        int j = A.length-1;
        while(i < j){
            int sum = A[i]+A[j];
            if(sum<K){
                maxSum = Math.max(maxSum,sum);
                i++;
            }else{
                j--;
            }
        }
     return maxSum;
    }
}

LeetCode - Reorder Data in Log Files

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: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]

Constraints:
  1. 0 <= logs.length <= 100
  2. 3 <= logs[i].length <= 100
  3. logs[i] is guaranteed to have an identifier, and a word after the identifier.

Solution :

Java Solution :



class Solution {
    public String[] reorderLogFiles(String[] logs) {
        Arrays.sort(logs,(log1,log2)->{
            String[] set1 = log1.split(" ",2);
            String[] set2 = log2.split(" ",2);
            boolean isCharacter1 = Character.isLetter(set1[1].charAt(0));
            boolean isCharacter2 = Character.isLetter(set2[1].charAt(0));
            if(isCharacter1 && isCharacter2){
                int cmp = set1[1].compareTo(set2[1]);
                if(cmp !=0) return cmp;
                return set1[0].compareTo(set2[0]);
            }
            return !isCharacter1 ? (!isCharacter2 ? 0 : 1) : -1;
        });
        return logs;
    }
}

Amazon Onsite Interview Questions

1.  Two Sum
2. Most Common Word
3. Reorder Log files
4.Trapping Rain Water
5.Copy List With Random Pointer
6.Number of Islands
7. Lowest common ancestor of Binary tree
8.Binary Tree Zig zag level order traversal
9. Word Ladder 1 , 2
10. word search 1  , 2
11. Meetings rooms 1 , 2
12. Kth largest element in array.
13. K closest points to Origin.
14.Longest Palindromic Substring.
15. LRC Cache
16. Tic Toc Toe
17. Leetcode all design questions.
18. Prison cells after N days.
19. word break 2
20.  stream of characters (DNA Sequence )
21.
Given a 2d array in which each row is sorted and rotated, you need to come up with an algorithm which efficiently sort the entire 2d matrix in descenting order.
eg:
input: arr[][] = {
{41, 45, 20, 21},
{1 ,2, 3, 4},
{30, 42, 43, 29 },
{16, 17, 19, 10}
}
output: {
{ 45, 43, 42, 41},
{30, 29, 21, 20},
{19, 17, 16, 10},
{4, 3, 2, 1}
}
Interviewer was expecting the solution to run with a complexity < O(n^3) solution.


23. https://leetcode.com/problems/top-k-frequent-elements/

nput is in <productId, timeStamp> format. So assume you have a list of productIDs and their timestamps which they were accessed:
[<product1, timestamp1>, <product2, timestamp2>, <product3, timestamp3>, ...]
Find the top K products purchased in the last one hour.

24. We have two Queues where each queue contains timestamp price pair. We have to return list of list[[price1, price 2]] for all those timestamps where abs(ts1-ts2) <= 1 second where ts1 and price1 are the from the first queue and ts2 and price2 are from the second queue.
Follow up:- one queue is slow

25.Deep copy of an N-ary tree.

public TreeNode clone(TreeNode root) {
  if (root == null) {
    return null;
  }

  TreeNode rootClone = new TreeNode(root.val);
  for (TreeNode child : root.children) {
    TreeNode childClone = clone(child);
    rootClone.children.add(childClone);
  }

  return rootClone;
}

private static class TreeNode {

  int val;
  List<TreeNode> children = new ArrayList<>();

  public TreeNode() {
  }

  public TreeNode(int val) {
    this.val = val;
  }
}
26.https://leetcode.com/problems/subsets/
Now the follow-up question is to remove that for loop from backtrack funtion and pass the indexes. I tried to keep i index by passing it to the function by couldn't figure out the index incrementing logic.
ay we have a machine which scans a printed word and assigns a probablity to each character of the word. For example, if we scan LBC, the machine produces the following map for the word (first list will be for the first char, second list for the second char etc.) :
{
 ['L': 90, 'I': 50, 'N': 10],      // for first character (L)
 ['B': 95, '8': 80, 'S': 15],      // for secodn character (B)
 ['C': 90, 'O': 90, 'D': 70]       // for third character (C)
}
Meaning for the first character there is a 90 percent chance that it is L, 50 percent that it is I etc. Given a list of Strings, return the word with the highest probablity based on this map. For example, if the list is {LBD, IBC, LSD}LBD should be returned (with the probablity of 90 + 95 + 70).
27. Consider that there are 26 tables, listed from A to Z. Each table is connected with table next to it. A connected to B, B to C so forth and so on till Z.
How will you connect table A and Z with minimum number of joins?
There are two anagram strings, what is the minimum number of swaps required to match one string to another? You can swap any 2 characters. What is time complexity?
Example 1:
Input: s1 = "AABC", s2 = "AACB"
Output: 1
Explanation: swap 'B' and 'C' AABC => AACB
29.Position: SDE2
Design a configuration management system
  • User should be able to add configuration
  • User should be able to delete configuration
  • User should be able to search for configuration
  • User should be able to subscribe to Configuration So that any updates in configuration will gets notfied to user
30.I have my amazon interview coming up for SDE in seattle. One of my friends recently went on-site in Seattle and was asked this question in OOD. I have not been able to find a good approach to this question. Any suggestions would be helpful
implemnet linux find command as an api ,the api willl support finding files that has given size requirements and a file with a certain format like
  1. find all file >5mb
  2. find all xml Assume file class { get name() directorylistfile() getFile() create a library flexible that is flexible Design clases,interfaces.
31. https://leetcode.com/problems/analyze-user-website-visit-pattern
32. Given an array of strings, you need to group isomorphic strings together.
Example:
Input: ["apple", "apply", "dog", "cog", "romi"]
Output: [["dog", "cog"], ["romi"], ["apple", "apply"]]
33. Load Packages

Algorithm Run Time Analysis

Algorithm Run Time Analysis:


ARTA is nothing but how much time the algorithm takes to run or to execute.

Based on the run time of the algorithm the efficiency of the algorithm is determined , this will be the deciding factor whether your algorithm is good or bad.

Based on ARTA , a algorithm can be improved to get better efficiency compared to your previous algorithm.


Practical Use Of Recursion Methodology

Where we use Recursion in Practical ?

Recursion is  heavily used in various areas.


  • We use in Stack example : Fibonacci Series
  • We use in Trees .  For Traversal , Insertion , Deletion , Searching.
  • We use in Quick Sort and Merge Sort.
  • Divide and Conquer -> Where bigger problem is divided into smaller chunks . Smaller chunks will be similar mostly.
  • In Dynamic Programming we use recursion where we divide bigger problem and solve smaller chunks and use to solve the bigger problem. 


   

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