forked from mission-peace/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Home
mission-peace edited this page Aug 12, 2014
·
279 revisions
###Arrays###
- Given two numbers in form of array add them - ArrayAddition.java
- Given stock prices for number of days BuySellStockProfit.java
- Buy sell stock once to maximize profit
- Buy sell stocks any number of times to maximum profit
- Given an array of elements check if elements in the array are consecutive or not. - CheckIfArrayElementsAreConsecutive.java
- Given elements in array divide elements into two groups of closest possible sum Conflict with TugOfWar - DivideNumbersInEqualGroupWithClosestSum.java
- Write a function to determine if array contains duplicate elements within k distance from each other - DuplicateWithinkIndices.java
- Given an array and a number k < n, find all elements occurring more than n by k times - FindElementsOccurringNByKTimesTetris.java
- Given a list of gas stations and amount of fuel they have, find a tour which travels all gas stations - GasStationCircle.java
- Given an unordered array of positive integers, create an algorithm that makes sure no group of integers of size bigger than M have the same integers - GroupElementsInSizeM.java
- Given an array find an increasing subsequence of length 3 which has maximum product - IncreasingSubsequnceOfLength3WithMaxProduct.java
- Given an array find maximum circular contiguous sum - KadaneWrapArray.java
- kth largest element in an unsorted array using quick select - KthElementInArray.java
- kth largest element in two sorted array - KthLargestInTwoSortedArray.java
- Print next greater element for every element in array - LargerElementOnRight.java
- Given an array of 0s and 1s find the largest subarray with equal number of 0s and 1s - LargestSubArrayWithEqual0sAnd1s.java
- Longest increasing subsequence in an array with O(logN) speed - LongestIncreasingSubSequenceOlogNMethod.java
- Given an array maximize i - j such that a[i] > a[j] - MaximumIminusJSuchThatAiGTAj.java
- Given an array, find maximum of all subarrays of size k - MaximumOfSubarrayOfSizeK.java
- Given an array of positive and negative numbers, find a subarray which has maximum product - MaxProductSubarray.java
- Given an array of size n, the array contains numbers in range from 0 to k-1 where k is a positive integer and k <= n. Find the maximum repeating number in this array - MaxRepeatingNumber.java
- Given an array and two numbers, find minimum distance between these numbers. There could duplicates of these numbers in array - MinimumDistanceBetweenTwoNumbers.java
- Find minimum length unsorted subarray, sorting which makes entire array sorted - MinimumSortedWhichSortsEntireArray.java
- Given array of 0 and non zero numbers, move all 0s to the end in O(n) time - MoveAllZerosToEnd.java
- Given an array, return a new array which has multiplication of all elements except own index - MultiplyAllFieldsExceptOwnPosition.java
- Given an unsorted array, find total number of triangles formed taking 3 elements of this array - NumberOfTrianglesInUnsortedArray.java
- Given an array with first negative and then positive numbers, position negative and positive numbers alternately - PositiveAndNegativeNumberAlternatively.java
- Given an array arr[] of size n where every element is in range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]] in O(n) time and O(1) space - RearrangeSuchThatArriBecomesArrArri.java
- Given an array with elements in range of 0 to n-1, one number is repeated and one number is missing. Find both the numbers - RepeatingAndMissingNumber.java
- Stable marriage problem - StableMarriageProblem.java
- Given an unsorted array of nonnegative numbers , find a contiguous subarray with given sum - SubarrayWithGivenSum.java
- Given an array, find triplet which sums to a given value - https://github.com/mission-peace/interview/blob/master/src/com/interview/array/TripletInArray.java
- Given a set of n integers, divide the set in two subsets of n/2 sizes each such that the difference of the sum of two subsets is as minimum as possible - Conflict with DivideNumbersInEqualGroupWithClosestSum - TugOfWar.java
- Given an unsorted array convert it into a < b > c < d > e < f > g fashion - ConvertAnArrayIntoDecreaseIncreaseFashion.java
###Binary Search###
- Given an arithmetic progression with one number mission find that missing number - ArithmeticProgressionSearch.java
- Search an element in sorted array - BinarySearch.java
- Search an element in array which is first increasing then decreasing then increasing or other way round - CircularBinarySearch.java
- Given a sorted array find total number of pairs whose difference is k - CountNDistinctPairsWithDifferenceK.java
- Given a sorted array with duplicates, find first occurrence of a given element - FirstOccurrenceOfNumberInSortedArray.java
- Find floor and ceiling of given element in sorted array - FloorAndCeilingSortedArray.java
- Find median of two sorted array of same size - MedianOfTwoSortedArray.java
- Find a missing number in array of consecutive numbers - MissingNumberInConsecutiveNumbers.java
- Find a value of function in which this monotonically increasing function becomes positive - MonotonicallyIncreasingFunctionBecomesPositive.java
- Find number of pairs where x^y > y^x - NumberOfPairWithXPowerYGreaterThanYPowerX.java
- Given an array find an element which is larger than both its neighbors - PeakElement.java
- Given an array which is sorted and rotated find an element - SortedAndRotatedArraySearch.java
- Minimum element in sorted and rotated array
###Bits###
- Add two number in binary representation - AddTwoNumberInBinaryRepresentation.java
- Given an integer and number k, right or left rotate bits in this integer by k - BitRotation.java
- Using byte array for storing information - ByteAsStorage.java
- Count number of set bits in an integer - CountBits.java
- Given a screen in form of byte array with width and start and end points of a horizontal line. Draw this line DrawHorizontalLine.java
- Given an array in which every number occurs 3 times find this one number occurring only once - FindNumberOccurringOnceOtherNumbers3Times.java
- Given two numbers M and N, insert M into N from i to j bits of N - InsertMintoNiTojBits.java
- Given an integer find next higher/lower integer with same number of set bits as original integer - NextHigherAndNextLowerWithSameNumberBits.java
- Given an integer find next power of 2 greater than this integer - NextPowerOf2.java
- Given an array find one/two number occurring odd number of times - NumberOccuringOddTimes.java
- Given two numbers M and N, how many bit flips are required to convert M into N - NumberOfBitsFlipToConvertNToM.java
- Convert a real number(with decimals) into a binary number - RealNumberToBinary.java
- Given an integer reverse bits of this integer - ReverseBits.java
- Given an integer swap its odd bits with even bits at every position - SwapOddEvenBits.java
- Given an integer and two numbers i and j, swap bits at these positions in this integer - SwapTwoBits.java
- Initially there is a number n. Two players start playing a game turn by turn. Each player has to replace the number n written on the board by n-2^k (for some k >= 0 such that 2^k < n) - WinnerWithBeautifulNumber.java
###Dynamic Programming###
- Given a sequence of words, and a limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly. AdjustWordsInLine.java
- Find longest bitonic subsequence in an array. Bitonic subsequence first increases and then decreases - BitonicSequence.java
- Given a long word which is made up of multiple words, split the long word into individual words - BreakMultipleWordsWithNoSpaceIntoSpace.java
- Coin changing problem. Given set of coins and a total t. - CoinChanging.java
- Total solutions possible to form t.
- Minimum numbers of coin needed to form t.
- Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1′s - CountNumberOfBinaryWithoutConsecutive1s.java
- Count number of trees that can be formed given a preorder sequence - CountNumberOfTreePreorder.java
- Count number of binary search trees formed by an array of size n - CountNumberOfTreesInBST.java
- Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces - CuttingRod.java
- Given n dice each with m faces, numbered from 1 to m, find the number of ways to get sum X. X is the summation of values on each face when all the dice are thrown - DiceThrowWays.java
- Given two strings of size m, n and set of operations replace (R), insert (I) and delete (D) all at equal cost. Find minimum number of edits (operations) required to convert one string into another - EditDistance.java
- Given number of floors and certain number of eggs, find the floor from which egg will break using minimum number of drops - EggDropping.java
- Given a bag which can only take certain weight W. Given list of items with their weights and price. Stuff these items in the bag such that it maximizes the value of bag - Knapsack01.java
- Given two strings. Find longest common subsequence/substring between the two strings - LongestCommonSubsequence.java
- Given an unsorted array. Find the longest increasing subsequence in this array - LongestIncreasingSubsequence.java
- Given a sequence, find the length of the longest palindromic subsequence in it - LongestPalindromicSubsequence.java
- Given array of matrices, find a sequence which will have minimum multiplication cost - MatrixMultiplicationCost.java
- Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array - MaxSumForNonAdjacentElements.java
- Given set of jobs with start and end interval and profit, how to maximize profit such that jobs in subset do not overlap - MaximizeProfitWithJob.java
- Find the longest chain which can be formed from a given set of pairs.In every pair, the first number is always smaller than the second number.Chain of pair (c, d) can follow another pair (a, b) if b < c - MaximumLengthChainPair.java
- Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts - MaximumProductCutting.java
- Given a matrix, find maximum size square sub matrix - MaximumSizeSubMatrix.java
- Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array such that the intgers in the subsequence are sorted in increasing order - MaximumSumSubsequence.java
- Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0) - MinCostPath.java
- Given an array of integers where each element represents the max number of steps that can be made forward from that element. Write a function to return the minimum number of jumps to reach the end of the array - MinJumpToReachEnd.java
- Given an array of gold coins with different values and two players. Each player picks gold coin from either side. Write an algorithm to maximize your winning chance - NPotGold.java
- Given a matrix. Find total paths to reach from 0,0 to m,n in this matrix - NumberOfPathsInMxNMatrix.java
- Finding the number of ways a given score could be reached for a game with 3 different ways of scoring (e.g. 3, 5 and 10 points) - NumberOfWaysToScorePoints.java 28.Given a sorted array keys[0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts, where freq[i] is the number of searches to keys[i]. Construct a binary search tree of all keys such that the total cost of all the searches is as small as possible - OptimalTreeSearch.java
- Given a string, partition the string with fewest cuts such that each partition is a palindrome - PalindromePartition.java
- Remove minimum number of elements from either end of array such that 2*min > max in this remaining elements of array - RemoveFromEndToMake2IntoMinGreaterThanMax.java
- Given a matrix, find a rectangular submatrix with maximum sum - SubArrayWithMaximumSum.java
- Given an array and a total. Tell if elements of this array can form this total - SubsetSum.java
- Given an array of X and Os. Find largest subsquare which is surrounded by Xs - SubsquareSurrounedByXs.java
- Given three strings, determine if first two strings can interleave to form third string - TwoStringInterleavingToFormThird.java
- Given a number n, find all numbers from 1 to n which are multiples of 2,3 or 5 only. UglyNumbers.java
- Given the mobile numeric keypad. You can only press buttons that are up,left,right or down to the current button.You are not allowed to press bottom row corner buttons (i.e. * and # ).Given a N find out the number of numbers possible of given length - PhoneDialNumberOfCombinationOfSizeK.java
###Graph###
- A vertex in an undirected connected graph is an articulation point (or cut vertex) iff removing it (and edges through it) disconnects the graph. ArticulationPoint.java
- Find shortest path from one vertex to all vertex using bellman ford algorithm - BellmanFordShortestPath.java
- Binary max heap - BinaryMaxHeap.java
- Binary min heap - BinaryMinHeap.java
- A Bipartite Graph is a graph whose vertices can be divided into two independent sets, U and V such that every edge (u, v) either connects a vertex from U to V or a vertex from V to U - BiparteGraph.java
- Design a game of boggle - Boggle.java
- An edge in an undirected connected graph is a bridge iff removing it disconnects the graph. Given a graph find all bridges in this graph - Bridge.java
- Given two words of equal length convert first word to second word in such a way that all intermediate words are in dictionary - ConvertOneWordToAnother.java
- Find cycle in directed graph - CycleInDirectedGraph.java
- Find cycle in undirected graph - CycleUndirectedGraph.java
- Given a directed acyclic graph(DAG) find shortest path from one vertex to all vertices - DAGShortestPathTopological.java
- Given a graph with weighted edges, find shortest path from one vertex to all vertices - DijkstraShortestPath.java
- Given a directed graph, return true if you can reach every node of graph from any node else false - DirectedGraphConnectivity.java
- Given a graph, tell if it is eulirian, semi eulirian or non eulirian - EulerianPathAndCircuit.java
- Given a 2D matrix of Xs and Os, convert all Os to Xs if it is surrounded by Xs - FillOsWIthXsIfSurroundedByXs.java
- Flood fill algorithm - FloodFillAlgorithm.java
- All pair shortest path using flyod warshall algorithm - FloydWarshallAllPairShortestPath.java
- Given a directed graph with source and end point, find maximum flow from source to end - FordFulkerson.java
- Graph basic data structure - Graph.java
- Given a graph, color each vertex such that neighboring vertex does not have same color - GraphColoring.java
- BSF and DFS graph traversal - GraphTraversal.java
- Given a graph, find hamiltonian cycle in the graph if it exists. Hamiltonian cycle in undirected graph starts and ends at same point and traverses each vertex exactly once - HamiltonianCycle.java
- Find minimum spanning tree using Krushkal's algorithm - KrushkalMST.java
- A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint - MaximumBiparteMatching.java
- Given a graph of 0s and 1s, find total number of islands of 1s - NumberOfIsland.java
- Given a graph, find total number of triangles in the graph - NumberofTriangles.java
- Path compression and rank algorithm - PathCompressionAndRank.java
- Prim's algorithm for minimum spanning tree - PrimMST.java
- Print all paths from source to destination in undirected graph - PrintAllPathFromSourceToDestination.java
- Given a directed graph, find strongly connected components of the graph - StronglyConnectedComponent.java
- Given a directed acyclic graph, sort is topologically - TopologicalSort.java
- Given a directed graph, find out if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the given graph - TransitiveClosure.java
###LinkList###
- Add two numbers represented by link list - AddNumberRepresentedByLinkList.java
- Create a copy of a link list in which one pointer points to next node while other pointer can point to any node in the list - CopyLinkListWIthArbitPointer.java
- Given a linklist, delete m nodes after every n nodes - DeleteNAfterMNodes.java
- Delete nodes which has greater value on right side - DeleteNodeWithGreaterValueOnRight.java
- Given a linklist in which down pointer could point to another linklist and this happens recursively, flatten this linklist - FlattenLinkList.java
- Given two linklist, insert nodes of second list into first list at alternate position - InsertNodesAtAlternatePosition.java
- Implement a LRU cache using linklist and map - LRUCache.java
- Basic link list structure - LinkList.java
- Sort linklist using merge sort - MergeSortLinkList.java
- Quick sort linklist - QuickSortSingleLinkList.java
- Remove duplicates from a sorted linklist - RemoveDuplicatesSortedList.java
- Given a linklist and k,reverse alternate k nodes in the linklist - ReverseAlternateKNodes.java
- Given a linklist, reverse alternate nodes and append it at the end - ReverseAlternateNodeAndAppendAtEnd.java
- Reverse every k nodes in a linklist - ReverseKNodes.java
- Sort a nearly sorted linklist - SortNearlySortedList.java
- Insert into sorted circular linklist - SortedCircularLinkList.java
- Given a sorted linklist, convert it into a balanced binary search tree - SortedLLToBalancedBST.java
- Stack with also support find/delete middle operation - StackWithLinkListMiddleOperation.java
- Given three linklist and a sum, find a triplet from each list which adds up to sum - TripletToSumInLinkList.java
###Multi Array###
- Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j] is 1 (or true) then make all the cells of ith row and jth column as 1 - Fill2DMatrixWith1.java
- Design game of life - GameOfLife.java
- Find the length of the longest chain of consecutive integers in an unsorted 2D square array (non-diagonal) - LongestConsecutiveIntegerInUnsorted2DArray.java
- Given a 2D array, create a new 2D array which joins first row elements with every other element from second row onwards - MatrixCalculation.java
- Given a 2D array, find sum of all rectangular and square sub matrix - MatrixFindAllSubSquareRectangleMatrix.java
- Print a 2D array in diagonal format - MatrixInDiagonalOrder.java
- Create a 2D array of alternating Xs and 0s rectangles - MatrixOf0sAnd1s.java
- Move in 2D array as per cell value - MoveCellPerCellValue.java
- Turn image by 90 degree - TurnImageBy90.java
###Numbers###
- Given a large number tell where it is an aggregate number or not - AggregateNumber.java
- Given an array of numbers, tell if there are 3 numbers which form arithmetic progression - ArithemeticProgressionExists.java
- Given a series of numbers as the input, the last one as the result.Use the rest numbers to calculate the result,only +, -, *, / are allowed - ArithmeticOperatorForFinalResult.java
- Given two numbers in form of an array, multiply them - ArrayMultiplication.java
- Given a number n and k, find binomial coefficient of n to k - BinomialCoefficient.java
- Covert a decimal number into any other base N < 10 - ConvertToBaseN.java
- Given a number n, find counts of 2 from 1 to n - CountNoOf2s.java
- Given a number n, find number of numbers which does not have digit 4 in them - CountNumbersNotIncluding4.java
- Given a dividend and a divisor, return remainder and quotient - DivisionWithoutDivisionOperator.java
- Given two numbers find their GCD(greatest common divisor) - EuclideanAlgoForGCD.java
- Given an array of numbers, generate a signature where D represent decrease and I represents increase. Now given Ds and Is generate pattern of number - GenerateSignature.java
- Given an array, find elements combining which forms largest multiple of 3 - https://github.com/mission-peace/interview/blob/master/src/com/interview/number/LargestMultipleOf3inArray.java
- Given a number n, tell if this number is a lucky number - LuckyNumbers.java
- Given an array of 3 numbers, find their median - https://github.com/mission-peace/interview/blob/master/src/com/interview/number/MedianOf3Number.java
- Write a program to determine whether n/2 distinctinctive pairs can be formed from given n integers where n is even and each pair's sum is divisible by given k - NBy2PairSumToK.java
- Given an array representing a number, find next larger palindrome which can be formed - NextLargestPalindrome.java
- Given a chinese number which never has 4, convert it into decimal format - NotIncluding4.java
- Given an array representing a number, return a new array consisting of same numbers but larger than this number - PermutationBiggerThanNumber.java
- Given two arrays representing numbers, convert first array into number which is next larger than second array - PermutationLargerThanGivenArray.java
- Calculate power function using divide and conquer - PowerFunction.java
- Given an array of numbers, arrange them in a way that yields the largest value - RearrangeNumberInArrayToFormLargestNumber.java
- Russian peasant multiplication - RussianPeasantMultiplication.java
- Smallest number greater than given number but all digits in increasing order - SmallestNumberGreaterThanGiveNumberIncreasingSequence.java
- Calculate square root of a number without using any library - SquareRoot.java
- Given a positive integer n, generate all possible unique ways to represent n as sum of positive integers -https://github.com/mission-peace/interview/blob/master/src/com/interview/number/UniquePartitionOfInteger.java