ashoklathwal / Code-for-Interview

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Code-for-Interview

My Solutions

Introduction

Hacking a Google Interview

Some New important Questions Added

  • Data structure: insert, remove, contains, get random element, all at O(1) Explanation

Linked list :

  • How will you detect cycle and remove it from the linked list Solution Explanation
  • Create a function that does addition where the numbers are represented as two linked lists.Solution Explanation
  • Insertion of a node in Linked List (On the basis of some constraints) Solution
  • Delete a given node in Linked List (under given constraints) Solution
  • Merge A Linked List Into Another Linked List At Alternate Positions Solution Explanation
  • Write a function to reverse a singly linked list and doubly linked listSolution
  • Reverse A List In Groups Of Given Size Solution
  • Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists Explanation
  • Merge Sort For Linked Lists Solution Explanation
  • Union And Intersection Of 2 Linked Lists Explanation
  • Write a function to get the intersection point of two Linked Lists Explanation
  • Select A Random Node from A Singly Linked List Explanation
  • Find middle element of linked list and delete it Solution
  • Segregate even and odd nodes in a Linked List Solution Explanation
  • Flattening a Linked List Solution
  • Sort numbers stored on different machines Explanation
  • Merge K sorted linked lists Explanation1 Explanation2
  • Sort a linked list of 0s, 1s and 2s Solution
  • Split a Circular Linked List into two halves Explanation
  • Sorted insert for circular linked list Explanation
  • Swap Kth node from beginning with Kth node from end in a Linked List Solution
  • Remove Dups: Write code to remove duplicates from an unsorted linked list. Explanation
  • Palindrome: Implement a function to check if a linked list is a palindrome. Explanation
  • Implement LRU Cache Solution
  • Decimal Equivalent of Binary Linked List
  • Pairwise swap elements of a given linked list
  • Swap nodes in a linked list without swapping data
  • Reverse alternate K nodes in a Singly Linked List
  • Swap alternate nodes in a Singly Linked List

Stack

Queue

  • Implement Queue using Stacks Explanation Que_Using_1_Stack
  • An Interesting Method to Generate Binary Numbers from 1 to n Solution
  • implement k Queues in a single array Explanation
  • Animal Shelter: An animal shelter, which holds only dogs and cats, operates on a strictly"first in, first out" basis. People must adopt either the "oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog,and dequeueCat. You may use the built-in Linked List data structure Solution
  • Construct Complete Binary Tree from its Linked List Representation Explanation
  • Find the first circular tour that visits all petrol pumps
  • Sliding Window Maximum (Maximum of all subarrays of size k) Solution Explanation
  • Minimum time required to rot all oranges

String

  • Count Possible Decodings of a given Digit Sequence Solution Explanation
  • Given a string, print out all its permutations(without duplicate in input Explanation
  • Print all permutations in sorted (lexicographic) order Solution Explanation
  • Reverse words in a given string Solution
  • Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? Explanation
  • Check Permutation: Given two strings, write a method to decide if one is a permutation of the other Explanation
  • Write a method to remove spaces from String Solution
  • URLify: Write a method to replace all spaces in a string with '%20: and that you are given the "true" length of the string Solution
  • Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. Solution
  • One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Solution
  • Given a string "aaabbbcc", compress it into "a3b3c2" in-place.Original Question Solution
  • String Rotation: Assume you have a method isSubst ring which checks if one word is a substring of another. Given two strings, 51 and 52, write code to check if 52 is a rotation of 51 using only one call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat"). Solution
  • Given a number, return all possible strings that the number could represent if 2 -> {A, B, C}, 4 -> {D, E, F}, and so on. (OR) return-all-possible-strings-that-the-phone-number-could-represent Solution Explanation
  • Write a function that parses a string into integer.Solution
  • Rearrange characters in a string such that no two adjacent are same Solution Explanation
  • Smallest substring of str containing all the characters in arr Solution Explanation
  • Anagrams
    • Check whether two strings are anagram of each other Solution
    • Given a sequence of words, print all anagrams together Solution
    • Anagram Substring Search (Or Search for all permutations) Solution
    • Remove minimum number of characters so that two strings become anagram Solution Explanation
    • Check if two strings are k-anagrams or not Solution Explanation
  • InterLeaving
  • Sort a string according to the order defined by another string Explanation
  • Given a sorted dictionary of an alien language, find order of characters
  • Lexicographic rank of a string
  • Print all possible words from phone digits
  • Check if two strings can become same after a swap in one string
  • An in-place algorithm for String Transformation
  • Given two strings, find if first string is a subsequence of second
  • Find Excel column name from a given column number
  • Check if a given string is a rotation of a palindrome
  • Remove a character from a string to make it a palindrome
  • Minimum insertions to form shortest palindrome
  • Recursively print all sentences that can be formed from list of word lists
  • Find the longest substring with k unique characters in a given string
  • Efficiently check if a string has duplicates without using any additional data structure
  • Rearrange a string so that all same characters become d distance away
  • Find if an array of strings can be chained to form a circle
  • find second most frequent character
  • Count substrings with same first and last characters
  • Find the missing number in a string of numbers with no separator
  • Distinct strings with odd and even changes allowed
  • Find all substring of a given String.
  • Find all palindromic substring of a given string.

Bitwise Manipulation

  • Count set bits in an integer Explanation
  • Conversion: Write a function to determine the number of bits you would need to flip to convert integer A to integer B. Solution
  • How to swap two numbers without using a temporary variable Explanation
  • Debugger: Explain what the following code does: ( (n & (n -1) ) == 0) Ans : It tells that number 'n' is power of 2 or not.
  • Insertion: You are given two 32-bit numbers, Nand M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2. Solution EXAMPLE Input: N = 10000000000,M = 10011, i = 2, j = 6 Output: N = 10001001100
  • Binary to String: Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR:' Solution
  • Flip Bit to Win: You have an integer and you can flip exactly 'm' bit from a 0 to a 1. Write code to find the length of the longest sequence of ls you could create. Solution
    EXAMPLE Input: 1775 (or: 11011101111) m = 1 Output: 8
  • Next Number: Given a positive integer, print the next smallest and the next largest number that have the same number of 1 bits in their binary representation. Solution Explanation
  • Pairwise Swap: Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 13 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on). Explanation
  • [NOT BIT] Find next greater number with same set of digits Solution Explanation
  • Draw Line: A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels to be stored in one byte. The screen has width w, where w is divisible by 8 (that is, no byte will be split across rows). The height of the screen, of course, can be derived from the length of the array and the width. Implement a function that draws a horizontal line from (xl, y) to (x2 J y) . The method signature should look something like: drawLine(byte[] screen, int width, int xl, int x2, int y)

Advanced data Structure

Arrays

  • Stock Buy Sell to Maximize Profit Solution Explanation
  • Given an array A[] and a number x, check for pair in A[] with sum as x Explanation
  • Count pairs with given sum Explanation
  • Count all distinct pairs with difference equal to k Explanation
  • Count pairs in a sorted array whose sum is less than x Explanation
  • Given a sorted array and a number x, find the pair in array whose sum is closest to x Explanation
  • Given two unsorted arrays, find all pairs whose sum is x Explanation for two sorted arrays Explanation
  • Find a triplet that sum to a given value Explanation
  • Find subarray with given sum Solution Explanation
  • Maximum Sum Subsequence Non-Adjacent Solution
  • Largest sum subarray with both +ve and -ve numbers Solution Explanation
  • Largest product subarray with both +ve and -ve numbers Solution
  • Find the Missing Number Explanation
  • Find the repeating and the missing Explanation
  • Find the two repeating elements in a given array Explanation
  • Find the smallest positive number missing from an unsorted array Explanation
  • Find the smallest missing number from sorted array Explanation
  • Convert an array to reduced form Solution Explanation
  • A Product Array Puzzle : Construct an array from PRODUCT of all elements of array except element at same index Explanation
  • Construct an array from XOR of all elements of array except element at same index Explanation
  • Given an array where every element occurs 'N' times, except one element which occurs only once. Find the element that occurs once Solution
  • Search an element in a sorted and rotated array Explanation
  • Find the minimum element in a sorted and rotated array Explanation
  • Program for array rotation Explanation
  • Sort elements by frequency Explanation1 Explanation2
  • Count frequencies of all elements in array in O(n) time and O(1) extra space Explanation
  • Duplicates in an array in O(n) and by using O(1) extra space Explanation
  • Rearrange an array so that arr[i] becomes arr[arr[i]] with O(n) time and O(1) extra space Explanation
  • Rearrange an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’ with O(n) time and O(1) extra space Solution Explanation
  • Maximum difference between two elements such that larger element appears after the smaller number Explanation
  • Segregate Even and Odd numbers Explanation
  • Sort an array of 0s, 1s and 2s Solution
  • Check for Majority Element Explanation
  • Given an array of of size n and a number k, find all elements that appear more than n/k times Solution Explanation
  • Given an array of 2n elements of which n elements are same and the remaining n elements are all different. Write program to find out the value which is present n times in the array Solution
  • Find runnning median in a stream of integer. Question Solution Explanation
  • Sort a nearly sorted (or K sorted) array Explanation
  • k^th largest element in stream Solution Explanation
  • Median of two sorted arrays Explanation
  • k^th largest/smallest element in an array Solution Explanation
  • k largest/smallest elements in an array Explanation
  • Sum of all elements between k1’th and k2’th smallest elements Explanation
  • Given an array arr[], find the maximum j – i such that arr[j] > arr[i] Explanation
  • Sort an array in wave form Explanation
  • Convert array into Zig-Zag fashion Explanation Ans: Using above approch just change opertor in if loop
  • Find a sorted subsequence of size 3 in linear time Explanation
  • Find a peak element Explanation
  • Search an element in an unsorted array using minimum number of comparisons Explanation
  • Merge k sorted arrays Solution Explanation
  • Connect n ropes with minimum cost Solution Explanation
  • Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted Explanation
  • Equilibrium index of an array Explanation
  • Primality
  • Design an efficient data structure for given operations
  • Find whether an array is subset of another array
  • Find the minimum distance between two numbers
  • Find the closest pair from two arrays
  • Minimum number of swaps required to sort an array
  • Minimum swaps to make two arrays identical
  • Check if a given array contains duplicate elements within k distance from each other
  • Online algorithm for checking palindrome in a stream
  • Pythagorean Triplet in an array
  • Find Union and Intersection of two unsorted arrays
  • Minimum number of swaps required for arranging pairs adjacent to each other
  • Trapping Rain Water
  • Convert array into Zig-Zag fashion
  • Minimize the maximum difference between the heights
  • Tic Tac Win: Design an algorithm to figure out if someone has won a game of tic-tac-toe

Mathematics

  • Program for nth Catalan Number and its application Explanation
  • Given GCD G and LCM L, find number of possible pairs (a, b) Explanation
  • Find smallest and largest number with given number of digits and sum of digits Exp1 Exp2
  • Find the smallest number whose digits multiply to a given number n Explanation

Dynamic Programming

  • Given an array of integers, find the Longest Increasing Subsequence of its items.
    1. Time complexity : O(n^2) using DP Solution Explanation
    2. Time complexity : O(n*log(n)) NOT DP Solution Explanation
  • Given two strings, find the Longest Common Subsequence between them. Solution Explanation
  • Given two strings, find the Longest Common Substring between them.
    1. Time complexity : O(m*n) using DP Solution Explanation
    2. Time complexity : O(m + n) using Suffix Tree
  • Given a string, find the Longest Palindromic Subsequence between them. Solution
  • Given a string, find the Longest Palindromic Substring between them.
    1. Time Complexity : O(n^2) NOT DP Solution
    2. Time Complexity : O(n) using Manacher’s Algorithm Solution Exp_1 Exp_2
  • Longest Bitonic Subsequence Solution
  • 0/1 Knapsack Problem Solution Exp_1 Exp_2
  • Matrix Chain Multiplication Solution Explanation-1 Explanation-2
  • Subset Sum Problem Solution Explanation
  • 'Partition problem' is to determine whether a given set can be partitioned into two subsets such that the sum of elements in both subsets is same.Solution
  • Partition a set into two subsets such that the difference of subset sums is minimum
  • Subset with sum divisible by k
  • Subset with no pair sum divisible by K
  • Maximum Length Bitonic Subarray
  • Optimal Binary Search Tree
  • Coin Changing problem
  • Minimum Edit Distance Exp1 Exp2
  • Minimum Cost Path Dynamic Programming Exp1 Exp2
  • Count of n digit numbers whose sum of digits equals to given sum Explanation
  • Weighted Job Scheduling
  • Cutting Rod dynamic programming
  • Egg Dropping Dynamic Programming
  • Text Justification Dynamic Programming
  • Word Break Problem Dynamic Programming
  • Box Stacking Dynamic Programming
  • Buy/Sell Stock With K transactions To Maximize Profit Dynamic Programming
  • Palindrome Partition Dynamic Programming
  • Maximum Sum Increasing Subsequence Dynamic Programming
  • Wildcard Matching Dynamic Programming
  • Regular Expression Dynamic Programming
  • String Interleaving Dynamic Programming
  • Optimal Strategy Game Pick from Ends of array Dynamic Programming
  • Burst Balloon Dynamic Programming[Leetcode]
  • Staircase Problem Fibonacci Series
  • Numbers WIthout Consecutive 1s in binary representation
  • Count Number of Binary Search Tree Possible given n keys Dynamic Programming
  • Total Ways in Matrix Dynamic Programming
  • Maximum profit by buying and selling a share at most twice
  • Sum Query in 2D Immutable Array Dynamic Programming
  • Count Number of Binary Tree Possible given Preorder Sequence length dynamic programming
  • Implement Fibonacci in bottom-up dynamic programming fashion.
  • Longest Mod path
  • Given a string, Find all distinct palindromic subsequence of a given string
  • Given a string, Find all distinct palindromic sub-strings of a given string
  • Given a string, Count All Palindrome Subsequence in a String
  • Given a string, Count All Palindrome Sub-Strings in a String

Matrix

  • Search in a row wise and column wise sorted matrix Explanation
  • Kth smallest element in a row-wise and column-wise sorted 2D array Explanation
  • Print a given matrix in spiral form Solution Explanation
  • Print K’th element in spiral form of matrix
  • Find the number of islands Solution Explanation
  • Find largest island Solution
  • Maximum size square binary sub-matrix with all 1s Solution Explanation
  • Finding the maximum square sub-matrix with all equal elements Solution
  • Maximum size rectangle binary sub-matrix with all 1s Solution Explanation
  • Maximum Subsquare With Sides as X Solution Explanation
  • Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 1, its entire row and column are set to 1. Explanation
  • Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. (an you do this in place? Explanation
  • Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix Explanation
  • Find the row with maximum number of 1s Explanation
  • Print maximum sum Rectangular sub-matrix from m*n matrix Solution Explanation
  • Print maximum sum sub-squares of size k x k Solution Explanation Exp2
  • Given an n x n square matrix, find sum of all sub-squares of size k x k
  • Implement Conway's game of life by predicting the next state of a matrix given its current state.
  • Program for Rank of Matrix

Sorting and searching

Trees

  • Algorithms on binary trees. Comprises of the following algorithms:
    • Given a node value, finds the node in tree using dfs
    • Pre-order traversal Iterative Traversal
    • In-order traversal
    • Post-order traversal
    • Checks if tree is a BST Explanation
    • Gets the height or depth of the BT Without recursion
    • Gets the Level of the BT
    • Get Odd and even level sum difference Solution
    • Checks if the tree is height balanced
    • Determines the Lowest Common Ancestor (LCA) of two nodes BT Explanation BST Explanation
    • Prints the tree level wise using BFS(level order traversal)
    • Prints the average value for each level in tree
    • Determines the in-order successor and predeccessor for a node in BST
    • find the k'th largest element in a Binary Search Tree(BST)?Explanation
    • Find Diameter of binary tree Explanation
  • Views of Binary Tree
    • Print Left view of BT
    • Print Right view of BT
    • Print Vertical order path of BT
    • Print top view of Binary tree Without HashMap
    • Print bottom view of Binary tree
  • Create mirror image of BT Explanation
  • check 2 tree are morror of each other or not Explanation
  • Check one BT is subset of another BT or not Explanation
  • Find Minimum or max Depth of a Binary Tree Min Max
  • Check whether a binary tree is a full binary tree or not Explanation
  • Check whether a given Binary Tree is Complete or not Explanation
  • Maximum Path Sum in a Binary Tree
  • Print all the paths
    • from root, with a specified sum in Binary tree
    • from root to leaf node with a specified sum in Binary tree
    • all k-sum paths in a binary tree
  • Given a binary tree, print out all of its root-to-leaf paths one per line. with recursion Without recursion
  • Serialize and Deserialize a Binary Tree Exp1 Exp2
  • Remove BST keys outside the given range Solution Explanation
  • Merge two BSTs with limited extra space Solution Exp1 Exp2
  • Recover Binary Search Tree Explanation
  • Flatten Binary Tree to Linked List Explanation1 Explanation2
  • Sorted LinkedList to Balanced BST Explanation
  • conversion of Sorted DLL to Balanced BST Explanation
  • Sorted Array to Balanced BST Explanation
  • Binary Tree to Doubly linked list Explanation
  • Convert a Binary Tree to a Circular Doubly Link List Explanation
  • Remove nodes on root to leaf paths of length < K
  • Tournament Tree (Winner Tree) and Binary Heap
  • Reverse alternate levels of a perfect binary tree
  • zig-zag traversal of binary tree
  • Connect nodes at same level
  • Boundary Traversal of binary tree
  • Convert a given Binary Tree to Doubly Linked List
  • Binary Tree to Binary Search Tree Conversion
  • Find the closest leaf in a Binary Tree
  • Construct Binary Tree from given Parent Array representation
  • Find the largest BST subtree in a given Binary Tree
  • Add all greater values to every node in a given BST
  • Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
  • How to handle duplicates in Binary Search Tree?
  • Count BST nodes that lie in a given range
  • Double Tree
  • Foldable Binary Trees
  • Print nodes at k distance from root
  • Print all nodes that are at distance k from a leaf node
  • Print all nodes at distance k from a given node
  • Get Level of a node in a Binary Tree
  • Check if a given Binary Tree is SumTree
  • Ternary Search Tree
  • Dynamic Programming | Set 26 (Largest Independent Set Problem)
  • Tree Isomorphism Problem
  • Find all possible interpretations of an array of digits
  • Difference between sums of odd level and even level nodes of a Binary Tree
  • Check if all leaves are at same level
  • Check if two nodes are cousins in a Binary Tree
  • Convert a Binary Tree to Threaded binary tree
  • Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
  • Mirror of n-ary Tree
  • Symmetric Tree (Mirror Image of itself)

Graphs

  • Algorithms on Graphs. Comprises of the following algorithms:
  • To detect cycle in a Graph Union Find
  • Boggle (Find all possible words in a board of characters)
  • Bridges in a Graph

Other Important Questions :

  • A kidnaper wishes to write a ransom note using letters from a magazine article. You are given with the ransom note and magazine article find whether kidnaper can write a note using the article or not Question Solution
  • Find the largest multiple of 3 from array of digits
  • Given an array of integers, return all possible subsets and powerset of length n. Explanation Solution
  • write a function that perforn left rotation in an array with k shift. Question Solution
  • Element of max subarray and primality Question Solution
  • Given two strings, and , that may or may not be of the same length, determine the minimum number of character deletions required to make and anagrams. Any characters can be deleted from either of the strings. Question Solution
  • Given the respective heights for each of the staircases in his house, find and print the number of ways he can climb each staircase. Question Solution
  • Lonely Integer OR Find the Number Occurring Odd Number of Times Question Solution Explanation
  • Check wheather number is prime or not Solution
  • Find nth prime number
  • Code a function that calculates the square root (2-point precision) of a given number(wihtout using the Math library). Follow up: Avoid redundant calculations by now optimizing your function with a caching mechanism. Babylonian method/Newton's method Solution Explanation
  • Write a function that raises one number to another number, i.e. the pow() function in log(n) time. Solution
  • Implement integer division without using / or % in O(logN).
  • given an array A[], and a rule array R[], A[] has some numbers... R[] has numbers from 0 to sizeof(A[])-1 (ie R[] has indices of A[] in shuffled order). So, by just looking at R[] and A[], you need to tell after how many rounds we will get original A[] if we apply R[] to it. ex. A[]={1,2,3} R[]={2,0,1} then answer should be 3
  • Given a number, obtain the next larger permutation and next lower permutation by swapping around the digits in the number.
  • Given a string, print out all its combinations.
  • How do you find the median of a very large dataset?
  • Fill an array based on frequency where elements are in range from 0 to n-1
  • If you have an incoming stream of numbers, how would you find the most frequent numbers on-the-fly?
  • Split a large string into valid words and store them in a dictionary. If the string cannot be split, return false. What’s your solution’s complexity?
  • What’s the computational complexity of finding a document’s most frequently used words?
  • If you’re given 10 TBs of unstructured customer data, how would you go about finding extracting valuable information from it?
  • How would you ‘disjoin’ two arrays (like JOIN for SQL, but the opposite)?
  • How would you use Python to read a very large tab-delimited file of numbers to count the frequency of each number?
  • Write a function that takes a sentence and prints out the same sentence with each word backwards in O(n) time.
  • Write a function that takes an array, splits the array into every possible set of two arrays, and prints out the max differences between the two array’s minima in O(n) time.
  • You have a room-full of balances and weights. Each balance weighs ten pounds and is considered perfectly balanced when the sum of weights on its left and right sides are exactly the same. You have placed some weights on some of the balances, and you have placed some of the balances on other balances. Given a description of how the balances are arranged and how much additional weight is on each balance, determine how to add weight to the balances so that they are all perfectly balanced. Original question
  • Let 1 represent ‘A’, 2 represents ‘B’, etc. Given a digit sequence, count the number of possible decodings of the given digit sequence.Question
  • Solve the “FizzBuzz” problem (needs no introduction).
  • Reverse an array without affecting special characters
  • All Possible Palindromic Partitions
  • Count triplets with sum smaller than a given value
  • Convert array into Zig-Zag fashion
  • Generate all possible sorted arrays from alternate elements of two given sorted arrays
  • Pythagorean Triplet in an array
  • Length of the largest subarray with contiguous elements
  • Find the smallest positive integer value that cannot be represented as sum of any subset of a given array
  • Smallest subarray with sum greater than a given value
  • Stock Buy Sell to Maximize Profit Explanation
  • implement Elevator
  • Find minimum average waiting time
  • Implement LRU Cache

About


Languages

Language:Java 100.0%