├── .gitattributes ├── .gitignore ├── Arrange.class ├── Arrange.java ├── Array2DPrimer1.class ├── Array2DPrimer1.java ├── ArrayLargestNum.class ├── ArrayLargestNum.java ├── ArrayMaxset.class ├── ArrayMaxset.java ├── Arrays ├── .gitattributes ├── .gitignore ├── Bucket.class ├── Bucket.java ├── DecimaltoArrayNums.class ├── DecimaltoArrayNums.java ├── Diagonal.class ├── Diagonal.java ├── Flip.java ├── Hotel$Interval.class ├── Hotel.class ├── Hotel.java ├── Interval.class ├── Interval.java ├── IntervalComparator.class ├── IntervalComparator.java ├── IntervalProblem.class ├── IntervalProblem.java ├── IntervalProblem2.class ├── IntervalProblem2.java ├── LargestNumber$Node.class ├── LargestNumber.class ├── LargestNumber.java ├── MaxDist.class ├── MaxDist.java ├── MaxGap.class ├── MaxGap.java ├── MaxProductPair.class ├── MaxProductPair.java ├── MaxSet.class ├── MaxSet.java ├── MaxSumContinguousSubArray.class ├── MaxSumContinguousSubArray.java ├── NArray.class ├── NArray.java ├── NextPermutation.class ├── NextPermutation.java ├── Pascal1.class ├── Pascal1.java ├── Pascal2.class ├── Pascal2.java ├── Plus1.class ├── Plus1.java ├── ProductOfEveryOtherInteger.class ├── ProductOfEveryOtherInteger.java ├── Reach.class ├── Reach.java ├── RepeatedElementInArray.class ├── RepeatedElementInArray.java ├── Rotate2D.class ├── Rotate2D.java ├── SetZeroRowAndColumn.class ├── SetZeroRowAndColumn.java ├── Spiral.class ├── Spiral.java ├── Spiral2.java ├── Wave.class └── Wave.java ├── BackTracking ├── Combinations.class ├── Combinations.java ├── Combinations2.class ├── Combinations2.java ├── NQueens.class ├── NQueens.java ├── PalinPart.class ├── PalinPart.java ├── Parenthesis.class ├── Parenthesis.java ├── Permutations.class ├── Permutations.java ├── SubSet$1.class ├── SubSet.class ├── SubSet.java ├── SubSet2$1.class ├── SubSet2.class └── SubSet2.java ├── BinarySearch.class ├── BinarySearch.java ├── BinarySearch ├── BinarySearch.java ├── Books.class ├── Books.java ├── FindTargetCount.class ├── FindTargetCount.java ├── GetMedianOfTwoSortedArrays.java ├── InsertPos.class ├── InsertPos.java ├── MedianArray.class ├── MedianArray.java ├── MedianOfTwoSortedArrays.class ├── MedianOfTwoSortedArrays.java ├── Paint.class ├── Paint.java ├── PaintKBoards.class ├── PaintKBoards.java ├── Pow.class ├── Pow.java ├── PowerUsingBinarySearch.class ├── PowerUsingBinarySearch.java ├── Search2D.class ├── Search2D.java ├── SearchRange.class ├── SearchRange.java ├── SearchRotated.class ├── SearchRotated.java ├── Sqrt.class └── Sqrt.java ├── BitManipulation ├── Divide.class ├── Divide.java ├── Num1Bits.class ├── Num1Bits.java ├── Rank2.java ├── RevBits.class ├── RevBits.java ├── Single.class ├── Single.java ├── Single2.class └── Single2.java ├── CheckPrime.class ├── CheckPrime.java ├── CountFrequencies.class ├── CountFrequencies.java ├── DynamicProgramming ├── Adjacent.class ├── Adjacent.java ├── Arrange2.java ├── AvgSet.class ├── AvgSet.java ├── Books.java ├── CoinChange2.class ├── CoinChange2.java ├── DataStructure.class ├── DataStructure.java ├── InterLeave.class ├── InterLeave.java ├── Jump1.class ├── Jump1.java ├── Jump2.class ├── Jump2.java ├── LongestIncreasingSequence.class ├── LongestIncreasingSequence.java ├── MaxPathTree.java ├── MaxProd.class ├── MaxProd.java ├── MaxRectangle.class ├── MaxRectangle.java ├── MinimumPath.class ├── MinimumPath.java ├── Palin2.class ├── Palin2.java ├── Paths2.java ├── Stairs.class ├── Stairs.java ├── Stocks1.class ├── Stocks1.java ├── Stocks2.class ├── Stocks2.java ├── Stocks3.class ├── Stocks3.java ├── StocksK.class ├── StocksK.java ├── UniqueTrees.class ├── UniqueTrees.java ├── WordBreak1.class ├── WordBreak1.java ├── WordBreak2.class └── WordBreak2.java ├── Excel1.class ├── Excel1.java ├── Factorial.class ├── Factorial.java ├── FirstMissingPositiveInteger.class ├── FirstMissingPositiveInteger.java ├── GCD.class ├── GCD.java ├── Graphs ├── Black.class ├── Black.java ├── CloneGraph.java ├── DirectedEdge.java ├── EdgeWeightedDigraph.java ├── FibSum.class ├── FibSum.java ├── FiniteAutomata.java ├── Knight.java ├── KnightEfficient.java ├── LevelOrder.java ├── StepNum.class ├── StepNum.java ├── Surrounding.class ├── Surrounding.java ├── WordLadder1.class ├── WordLadder1.java ├── WordLadder2.class ├── WordLadder2.java ├── WordNode.class ├── WordNode.java ├── WordSearch.class ├── WordSearch.java ├── WordSearch1.class └── WordSearch1.java ├── GreedyAlgorithms ├── Bulbs.class ├── Bulbs.java ├── Candy.class ├── Candy.java ├── Gas.class ├── Gas.java ├── Majority.class ├── Majority.java ├── MaxProduct3.class ├── MaxProduct3.java ├── Mice$Mices.class ├── Mice.class ├── Mice.java ├── Seats.class └── Seats.java ├── Hashing ├── Anagrams.class ├── Anagrams.java ├── ColorFull.class ├── ColorFull.java ├── CopyList.java ├── Equal$Pair.class ├── Equal.class ├── Equal.java ├── FourSum.class ├── FourSum.java ├── Fraction.class ├── Fraction.java ├── LSZero.class ├── LSZero.java ├── Points.class ├── Points.java ├── RandomListNode.java ├── RepeatString.class ├── RepeatString.java ├── SubString.class ├── SubString.java ├── SubstringCount.class ├── SubstringCount.java ├── TwoSum$Node.class ├── TwoSum.class ├── TwoSum.java ├── ValidSudoku.class └── ValidSudoku.java ├── HeapsAndMaps ├── LRU.class ├── LRU.java ├── ListNode.java ├── MergeKList.java ├── Node.class └── Node.java ├── LargestNumber.class ├── LargestNumber.java ├── LargestPairSum.class ├── LargestPairSum.java ├── LinkedLists ├── AddNumbers.java ├── ListCycle.java ├── ListNode.java ├── Merge.java ├── PartitionList.java ├── RemDuplicatesLink.java ├── ReorderList.java └── ReverseLinkedList.java ├── Linkedin ├── Complement.class ├── Complement.java ├── CountCommonCharacters.class ├── CountCommonCharacters.java ├── EditDistance.class ├── EditDistance.java ├── EvaluateReversePolishNotation.class ├── EvaluateReversePolishNotation.java ├── KthSmallestElement.class ├── KthSmallestElement.java ├── LevelOrderTraversal.java ├── ListCycle.java ├── LongestCommonPrefix.class ├── LongestCommonPrefix.java ├── MaxProductSubArray.class ├── MaxProductSubArray.java ├── MaxSumContiguousArray.class ├── MaxSumContiguousArray.java ├── MinimumDistance.class ├── MinimumDistance.java ├── MinimumWindowSubString.class ├── MinimumWindowSubString.java ├── NumberOfTriangles.class ├── NumberOfTriangles.java ├── Permutations.class ├── Permutations.java ├── PowerFunction.class ├── PowerFunction.java ├── ReverseWords.class ├── ReverseWords.java ├── SequenceNumbers.class ├── SequenceNumbers.java ├── SortedAndRotated.class ├── SortedAndRotated.java ├── StrictlyLargerTarget.class ├── StrictlyLargerTarget.java ├── Uber.class ├── Uber.java ├── UnionIntersectLists.java └── java ├── Math ├── AllPrimes.class ├── AllPrimes.java ├── DecimalToBinary.class ├── DecimalToBinary.java ├── Factors.class ├── Factors.java ├── Mode.class ├── Mode.java ├── Power2.class ├── Power2.java ├── PrimeSum.class ├── PrimeSum.java ├── Rank.class ├── Rank.java ├── Rank2.class ├── Rank2.java └── Rank2Efficient.java ├── Merge.class ├── Merge.java ├── NearestSmallerNumbers.class ├── NearestSmallerNumbers.java ├── Palindrome.class ├── Palindrome.java ├── Paths.class ├── Paths.java ├── PrintMissing.class ├── PrintMissing.java ├── PythagoreanTriplet.class ├── PythagoreanTriplet.java ├── Repeat3.class ├── Repeat3.java ├── ReverseInteger.class ├── ReverseInteger.java ├── Stack$1.class ├── Stack$ListIterator.class ├── Stack$Node.class ├── Stack.class ├── Stack.java ├── StacksAndQueues ├── Braces.class ├── Braces.java ├── EvaluateExpression.class ├── EvaluateExpression.java ├── Histogram.class ├── Histogram.java ├── MinStack.java ├── Rain.class ├── Rain.java ├── SimplifyPath.class ├── SimplifyPath.java ├── SlidingMax.class ├── SlidingMax.java ├── ValidParanthesis.class └── ValidParanthesis.java ├── Strings ├── AToI.class ├── AToI.java ├── AddBinary.class ├── AddBinary.java ├── CountSay.class ├── CountSay.java ├── IPAddress.class ├── IPAddress.java ├── Int2Roman.class ├── Int2Roman.java ├── LCP.class ├── LCP.java ├── LenghLast.class ├── LenghLast.java ├── LongestPalindrome.class ├── LongestPalindrome.java ├── MaxWeightTransformation.class ├── MaxWeightTransformation.java ├── Multiply.class ├── Multiply.java ├── Palindrome.class ├── Palindrome.java ├── PerttyJson.class ├── PerttyJson.java ├── Power.class ├── Power.java ├── RevWord.class ├── RevWord.java ├── RomanToInt.class ├── RomanToInt.java ├── SecondSmallestNumber.class ├── SecondSmallestNumber.java ├── SparseNumber.class ├── SparseNumber.java ├── StrStr.class ├── StrStr.java ├── TestJust.class ├── TestJust.java ├── ValidNumber.class ├── ValidNumber.java ├── Version.class ├── Version.java ├── ZigZag.class └── ZigZag.java ├── Trees ├── ArrayBST.java ├── Balanced.java ├── BinaryTree1.java ├── BinaryTree2.java ├── Cartesian.java ├── Flatten.java ├── InOrder.java ├── LCA.java ├── List2Tree.java ├── Majority.java ├── MaxDepth.java ├── MinDepth.java ├── NextPointer2.java ├── Order$Person.class ├── Order.class ├── Order.java ├── Path2.java ├── PostOrder.java ├── PreOrder.java ├── Prefix.class ├── Prefix.java ├── Recover.java ├── SameTree.java ├── SumRootLeaf.class ├── SumRootLeaf.java ├── TreeIterator.java ├── TreeNode.class ├── TreeNode.java ├── TreeTopView.java ├── UnivalTree.java └── ZigZagTree.java ├── TwoPointers ├── Array3Pointer.class ├── Array3Pointer.java ├── Container.class ├── Container.java ├── DiffK.class ├── DiffK.java ├── IntersectArr.class ├── IntersectArr.java ├── Longest1sWithKFlips.class ├── Longest1sWithKFlips.java ├── MaxOne.class ├── MaxOne.java ├── Merge.class ├── Merge.java ├── RemElm.class ├── RemElm.java ├── RemoveDuplicates.class ├── RemoveDuplicates.java ├── RemoveDuplicates2.class ├── RemoveDuplicates2.java ├── SortColor.class ├── SortColor.java ├── ThreeSum.class ├── ThreeSum.java ├── ThreeSumZero.class └── ThreeSumZero.java ├── UnionAndIntersection.class └── UnionAndIntersection.java /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear on external disk 35 | .Spotlight-V100 36 | .Trashes 37 | 38 | # Directories potentially created on remote AFP share 39 | .AppleDB 40 | .AppleDesktop 41 | Network Trash Folder 42 | Temporary Items 43 | .apdisk 44 | -------------------------------------------------------------------------------- /Arrange.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrange.class -------------------------------------------------------------------------------- /Array2DPrimer1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Array2DPrimer1.class -------------------------------------------------------------------------------- /Array2DPrimer1.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | public class Array2DPrimer1{ 3 | public ArrayList> performOps(ArrayList> A) { 4 | ArrayList> B = new ArrayList>(); 5 | for (int i = 0; i < A.size(); i++) { 6 | B.add(new ArrayList()); 7 | 8 | for (int j = 0; j < A.get(i).size(); j++) { 9 | B.get(i).add(0); 10 | } 11 | 12 | for (int j = 0; j < A.get(i).size(); j++) { 13 | B.get(i).set(A.get(i).size() - 1 - j, A.get(i).get(j)); 14 | } 15 | } 16 | return B; 17 | } 18 | 19 | public static void main(String[] args){ 20 | ArrayList> A =new ArrayList>(); 21 | int k = 1; 22 | for(int i = 0; i < 3; i++){ 23 | A.add(new ArrayList()); 24 | for(int j = 0; j < 4; j++){ 25 | A.get(i).add(k); 26 | k++; 27 | } 28 | } 29 | for (int i = 0; i < A.size(); i++) { 30 | for (int j = 0; j < A.get(i).size(); j++) { 31 | System.out.print(A.get(i).get(j) + " "); 32 | } 33 | System.out.println(); 34 | } 35 | System.out.println(); 36 | Array2DPrimer1 p = new Array2DPrimer1(); 37 | ArrayList> B = p.performOps(A); 38 | for (int i = 0; i < B.size(); i++) { 39 | for (int j = 0; j < B.get(i).size(); j++) { 40 | System.out.print(B.get(i).get(j) + " "); 41 | } 42 | System.out.println(); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /ArrayLargestNum.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/ArrayLargestNum.class -------------------------------------------------------------------------------- /ArrayLargestNum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a list of non negative integers, arrange them such that they form the largest number. 3 | 4 | For example: 5 | 6 | Given [3, 30, 34, 5, 9], the largest formed number is 9534330. 7 | 8 | Note: The result may be very large, so you need to return a string instead of an integer. 9 | */ 10 | public class ArrayLargestNum{ 11 | public static String largestNumber(Integer[] a){ 12 | String result = "0"; 13 | //String temp = ""; 14 | int N = a.length; 15 | for(int i = 0; i < N; i++) { 16 | String temp = Integer.toString(a[i]); 17 | for(int j = 0; j < N; j++) { 18 | if(i != j){ 19 | temp = temp + Integer.toString(a[j]); 20 | } 21 | } 22 | System.out.println(temp); 23 | if(Integer.parseInt(temp) > Integer.parseInt(result)) 24 | result = temp; 25 | } 26 | return result; 27 | 28 | } 29 | public static void main(String[] args){ 30 | Integer[] a = {3, 30, 34, 5, 9}; 31 | Merge m = new Merge(); 32 | m.sort(a); 33 | System.out.println(ArrayLargestNum.largestNumber(a)); 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /ArrayMaxset.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/ArrayMaxset.class -------------------------------------------------------------------------------- /Arrays/.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /Arrays/.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear on external disk 35 | .Spotlight-V100 36 | .Trashes 37 | 38 | # Directories potentially created on remote AFP share 39 | .AppleDB 40 | .AppleDesktop 41 | Network Trash Folder 42 | Temporary Items 43 | .apdisk 44 | -------------------------------------------------------------------------------- /Arrays/Bucket.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Bucket.class -------------------------------------------------------------------------------- /Arrays/Bucket.java: -------------------------------------------------------------------------------- 1 | class Bucket { 2 | int low; 3 | int high; 4 | public Bucket() { 5 | low = -1; 6 | high = -1; 7 | } 8 | } -------------------------------------------------------------------------------- /Arrays/DecimaltoArrayNums.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/DecimaltoArrayNums.class -------------------------------------------------------------------------------- /Arrays/DecimaltoArrayNums.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class DecimaltoArrayNums{ 3 | public static void main(String[] args){ 4 | ArrayList result = exp("7496314.4356"); 5 | 6 | System.out.print(result ); 7 | 8 | } 9 | public static ArrayList exp(String n) { 10 | String[] arr= new String[2]; 11 | if(n.contains(".")){ 12 | arr = n.split("."); 13 | } 14 | else{ 15 | arr[0] = n; 16 | } 17 | ArrayList result = new ArrayList(); 18 | String pattern = "^\\d*.?\\d*"; 19 | System.out.println("String matches: " + n.matches(pattern) + " " + arr[0]); 20 | if(!n.matches(pattern)) 21 | return result; 22 | 23 | //System.out.println("array length: " + arr.length); 24 | if(arr.length > 0){ 25 | System.out.println("entered if"); 26 | for(int i = 0; i < arr[0].length(); i++){ 27 | if(arr[0].charAt(i) != '0'){ 28 | int cal = (int)(Math.pow(10,(arr[0].length() - i-1))) * (arr[0].charAt(i)-'0'); 29 | System.out.println("cal: " + cal); 30 | result.add(Integer.toString(cal)); 31 | } 32 | } 33 | if(arr.length > 1){ 34 | for(int j = 0; j < arr[1].length(); j++){ 35 | double calculate = Math.pow(0.1, j+1) * (arr[1].charAt(j)-'0'); 36 | System.out.println("calculate: " + calculate); 37 | result.add(Double.toString(calculate)); 38 | } 39 | } 40 | } 41 | return result; 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /Arrays/Diagonal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Diagonal.class -------------------------------------------------------------------------------- /Arrays/Flip.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Flip.java -------------------------------------------------------------------------------- /Arrays/Hotel$Interval.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Hotel$Interval.class -------------------------------------------------------------------------------- /Arrays/Hotel.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Hotel.class -------------------------------------------------------------------------------- /Arrays/Interval.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Interval.class -------------------------------------------------------------------------------- /Arrays/Interval.java: -------------------------------------------------------------------------------- 1 | public class Interval { 2 | int start; 3 | int end; 4 | Interval() { start = 0; end = 0; } 5 | Interval(int s, int e) { start = s; end = e; } 6 | } -------------------------------------------------------------------------------- /Arrays/IntervalComparator.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/IntervalComparator.class -------------------------------------------------------------------------------- /Arrays/IntervalComparator.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class IntervalComparator implements Comparator{ 3 | public int compare(Interval i1, Interval i2){ 4 | return i1.start - i2.start; 5 | } 6 | } -------------------------------------------------------------------------------- /Arrays/IntervalProblem.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/IntervalProblem.class -------------------------------------------------------------------------------- /Arrays/IntervalProblem.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a collection of intervals, merge all overlapping intervals. 3 | * 4 | For example: 5 | 6 | Given [1,3],[2,6],[8,10],[15,18], 7 | 8 | return [1,6],[8,10],[15,18]. 9 | 10 | Make sure the returned intervals are sorted. 11 | */ 12 | import java.util.*; 13 | 14 | public class IntervalProblem{ 15 | 16 | public ArrayList merge(ArrayList intervals) { 17 | if(intervals == null || intervals.size() <= 1) 18 | return intervals; 19 | Collections.sort(intervals, new IntervalComparator()); 20 | ArrayList result = new ArrayList(); 21 | Stack s = new Stack(); 22 | Interval prev = intervals.get(0); 23 | for(int i = 1; i < intervals.size(); i++){ 24 | Interval current = intervals.get(i); 25 | if(prev.end >= current.start){ 26 | Interval merged = new Interval(prev.start, Math.max(prev.end, current.end)); 27 | prev = merged; 28 | } 29 | else{ 30 | result.add(prev); 31 | prev = current; 32 | } 33 | } 34 | result.add(prev); 35 | return result; 36 | } 37 | 38 | public static void main(String[] args){ 39 | IntervalProblem ip = new IntervalProblem(); 40 | ArrayList intervals = new ArrayList(); 41 | intervals.add(new Interval(1, 3)); 42 | intervals.add(new Interval(2, 6)); 43 | intervals.add(new Interval(8, 10)); 44 | intervals.add(new Interval(15, 18)); 45 | ArrayList result = ip.merge(intervals); 46 | for(int i =0; i < result.size(); i++){ 47 | System.out.printf("[%d, %d] ", result.get(i).start, result.get(i).end); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /Arrays/IntervalProblem2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/IntervalProblem2.class -------------------------------------------------------------------------------- /Arrays/LargestNumber$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/LargestNumber$Node.class -------------------------------------------------------------------------------- /Arrays/LargestNumber.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/LargestNumber.class -------------------------------------------------------------------------------- /Arrays/MaxDist.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/MaxDist.class -------------------------------------------------------------------------------- /Arrays/MaxGap.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/MaxGap.class -------------------------------------------------------------------------------- /Arrays/MaxProductPair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/MaxProductPair.class -------------------------------------------------------------------------------- /Arrays/MaxProductPair.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | public class MaxProductPair { 5 | public static int maxProduct(int[] a) { 6 | int n = a.length; 7 | if(n < 2){ 8 | System.out.println("No pairs exist"); 9 | return 0; 10 | } 11 | if(n == 2) 12 | return a[0] * a[1]; 13 | int firstMax = Integer.MIN_VALUE; 14 | int secondMax = Integer.MIN_VALUE; 15 | 16 | int firstMin = Integer.MAX_VALUE; 17 | int secondMin = Integer.MAX_VALUE; 18 | 19 | for(int i = 0; i < n; i++) { 20 | if(a[i] > firstMax) { 21 | secondMax = firstMax; 22 | firstMax = a[i]; 23 | } 24 | else if(a[i] > secondMax) { 25 | secondMax = a[i]; 26 | } 27 | 28 | if(a[i] < firstMin) { 29 | secondMin = firstMin; 30 | firstMin = a[i]; 31 | } 32 | else if(a[i] < secondMax) { 33 | secondMin = a[i]; 34 | } 35 | // if(a[i] < 0 && Math.abs(a[i]) > Math.abs(firstMin)) { 36 | // secondMin = firstMin; 37 | // firstMin = a[i]; 38 | // } 39 | // else if(a[i] < 0 && Math.abs(a[i]) > Math.abs(secondMin)) 40 | // secondMin = a[i]; 41 | } 42 | System.out.printf("firstMax : %d, secondMax : %d \n", firstMax, secondMax); 43 | System.out.printf("firstMin : %d, secondMin : %d \n", firstMin, secondMin); 44 | return Math.max(firstMin * secondMin, firstMax * secondMax); 45 | 46 | } 47 | public static void main(String[] args) { 48 | int[] a = {-1, -3, -4, 2, 0, -5}; 49 | System.out.println(maxProduct(a)); 50 | } 51 | } -------------------------------------------------------------------------------- /Arrays/MaxSet.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/MaxSet.class -------------------------------------------------------------------------------- /Arrays/MaxSumContinguousSubArray.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/MaxSumContinguousSubArray.class -------------------------------------------------------------------------------- /Arrays/NArray.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/NArray.class -------------------------------------------------------------------------------- /Arrays/NextPermutation.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/NextPermutation.class -------------------------------------------------------------------------------- /Arrays/Pascal1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Pascal1.class -------------------------------------------------------------------------------- /Arrays/Pascal1.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Pascal1.java -------------------------------------------------------------------------------- /Arrays/Pascal2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Pascal2.class -------------------------------------------------------------------------------- /Arrays/Pascal2.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Pascal2.java -------------------------------------------------------------------------------- /Arrays/Plus1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Plus1.class -------------------------------------------------------------------------------- /Arrays/Plus1.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Plus1.java -------------------------------------------------------------------------------- /Arrays/ProductOfEveryOtherInteger.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/ProductOfEveryOtherInteger.class -------------------------------------------------------------------------------- /Arrays/ProductOfEveryOtherInteger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | public class ProductOfEveryOtherInteger { 5 | public static void multiply(int[] a) { 6 | int[] result = new int[a.length]; 7 | 8 | int temp = 1; 9 | 10 | for(int i = 0; i < result.length; i++){ 11 | result[i] = temp; 12 | temp *= a[i]; 13 | } 14 | 15 | for(int i = 0; i < result.length; i++) 16 | System.out.print(result[i] + " "); 17 | System.out.println(); 18 | temp = 1; 19 | for(int i = result.length - 1 ; i >= 0; i--){ 20 | result[i] = result[i] * temp; 21 | temp *= a[i]; 22 | } 23 | for(int i = 0; i < result.length; i++) 24 | System.out.print(result[i] + " "); 25 | System.out.println(); 26 | } 27 | public static void main(String[] args){ 28 | int[] a = {1, 7, 3, 4}; 29 | int[] result = new int[a.length]; 30 | for(int i = 0; i < a.length; i++) { 31 | result[i] = 1; 32 | for(int j = 0; j < a.length; j++) { 33 | if(i != j) 34 | result[i] *= a[j]; 35 | } 36 | } 37 | multiply(a); 38 | // for(int i = 0; i < a.length; i++) 39 | // System.out.print(result[i] + " "); 40 | // System.out.println(); 41 | 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Arrays/Reach.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Reach.class -------------------------------------------------------------------------------- /Arrays/Reach.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Reach.java -------------------------------------------------------------------------------- /Arrays/RepeatedElementInArray.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/RepeatedElementInArray.class -------------------------------------------------------------------------------- /Arrays/RepeatedElementInArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a read only set of n + 1 integers between 1 and n, find one number that repeats in linear time using less then O(n) space and traversing the stream sequentially O(1) times. 3 | * 4 | Sample Input: 5 | 6 | [3 4 1 4 1] 7 | Sample Output: 8 | 9 | 1 10 | */ 11 | import java.util.*; 12 | public class RepeatedElementInArray{ 13 | // public static int repeatedNumber(final List A) { 14 | // for(int i = 0; i < A.size(); i++){ 15 | // if(A.get(Math.abs(A.get(i))) > 0) 16 | // A.set(Math.abs(A.get(i)), -1*A.get(Math.abs(A.get(i)))); 17 | // else 18 | // return Math.abs(A.get(i)); 19 | // } 20 | // return 0; 21 | // } 22 | public static int repeatedNumber(final List A) { 23 | int[] count = new int[A.size()]; 24 | for(int i = 0; i < A.size(); i++){ 25 | if(count[A.get(i)] == 1) 26 | return A.get(i); 27 | else 28 | count[A.get(i)] = 1; 29 | } 30 | return 0; 31 | } 32 | public static void main(String[] args){ 33 | List A = new ArrayList(); 34 | A.add(3); 35 | A.add(4); 36 | A.add(1); 37 | A.add(2); 38 | A.add(4); 39 | System.out.println(repeatedNumber(A)); 40 | } 41 | } -------------------------------------------------------------------------------- /Arrays/Rotate2D.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Rotate2D.class -------------------------------------------------------------------------------- /Arrays/SetZeroRowAndColumn.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/SetZeroRowAndColumn.class -------------------------------------------------------------------------------- /Arrays/Spiral.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Spiral.class -------------------------------------------------------------------------------- /Arrays/Spiral2.java: -------------------------------------------------------------------------------- 1 | public class Spiral2{ 2 | public ArrayList spiralOrder(final List> A) { 3 | ArrayList result = new ArrayList(); 4 | } 5 | 6 | } -------------------------------------------------------------------------------- /Arrays/Wave.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Arrays/Wave.class -------------------------------------------------------------------------------- /BackTracking/Combinations.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/Combinations.class -------------------------------------------------------------------------------- /BackTracking/Combinations.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/Combinations.java -------------------------------------------------------------------------------- /BackTracking/Combinations2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/Combinations2.class -------------------------------------------------------------------------------- /BackTracking/Combinations2.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/Combinations2.java -------------------------------------------------------------------------------- /BackTracking/NQueens.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/NQueens.class -------------------------------------------------------------------------------- /BackTracking/NQueens.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/NQueens.java -------------------------------------------------------------------------------- /BackTracking/PalinPart.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/PalinPart.class -------------------------------------------------------------------------------- /BackTracking/PalinPart.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/PalinPart.java -------------------------------------------------------------------------------- /BackTracking/Parenthesis.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/Parenthesis.class -------------------------------------------------------------------------------- /BackTracking/Parenthesis.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses of length 2*n. 3 | * 4 | For example, given n = 3, a solution set is: 5 | 6 | "((()))", "(()())", "(())()", "()(())", "()()()" 7 | Make sure the returned list of strings are sorted. 8 | */ 9 | import java.util.*; 10 | public class Parenthesis{ 11 | public static ArrayList generateParenthesis(int a) { 12 | ArrayList result = new ArrayList(); 13 | for(int i =1; i <= a; i++) 14 | Parenth("", 0, 0, i, result, a); 15 | 16 | return result; 17 | } 18 | private static void Parenth(String output, int open, int close, int pairs, ArrayList result, int a){ 19 | System.out.println("output: " + output); 20 | if(open == pairs && close == pairs && output.length() == 2*a){ 21 | System.out.println("\t Adding to result"); 22 | result.add(output); 23 | } 24 | else{ 25 | if(open < pairs){ 26 | System.out.println("\t Adding ( "); 27 | Parenth(output + "(", open + 1, close, pairs, result, a); 28 | } 29 | if(close < open){ 30 | System.out.println("\t Adding ) "); 31 | Parenth(output + ")", open, close + 1, pairs, result, a); 32 | } 33 | } 34 | } 35 | public static void main(String[] args){ 36 | int a = Integer.parseInt(args[0]); 37 | ArrayList result = generateParenthesis(a); 38 | System.out.println("*********Result*******"); 39 | for(String s: result) 40 | System.out.println(s); 41 | } 42 | } -------------------------------------------------------------------------------- /BackTracking/Permutations.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/Permutations.class -------------------------------------------------------------------------------- /BackTracking/SubSet$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/SubSet$1.class -------------------------------------------------------------------------------- /BackTracking/SubSet.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/SubSet.class -------------------------------------------------------------------------------- /BackTracking/SubSet2$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/SubSet2$1.class -------------------------------------------------------------------------------- /BackTracking/SubSet2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BackTracking/SubSet2.class -------------------------------------------------------------------------------- /BinarySearch.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch.class -------------------------------------------------------------------------------- /BinarySearch.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | public class BinarySearch { 3 | 4 | public static int rank(int key, int[] a){ 5 | int lo = 0; 6 | int hi = a.length - 1; 7 | 8 | while(lo <= hi){ 9 | int mid = (lo+hi)/2; 10 | if(key > a[mid]) lo = mid+1; 11 | else if(key < a[mid]) hi = mid-1; 12 | else return mid; 13 | } 14 | return -1; 15 | 16 | } 17 | public static void main(String[] args) { 18 | // TODO Auto-generated method stub 19 | In in = new In(); 20 | int[] whiteList = in.readInts(args[0]); 21 | Arrays.sort(whiteList); 22 | while(!StdIn.isEmpty()){ 23 | int key = StdIn.readInt(); 24 | if(rank(key,whiteList) < 0){ 25 | StdOut.println(key); 26 | } 27 | } 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /BinarySearch/BinarySearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Write an efficient algorithm that searches for a value in an m x n matrix. 3 | 4 | This matrix has the following properties: 5 | > 1. Integers in each row are sorted from left to right. 6 | > 7 | > 2. The first integer of each row is greater than or equal to the last integer of the previous row. 8 | 9 | Example: 10 | 11 | Consider the following matrix: 12 | 13 | [ 14 | [1, 3, 5, 7], 15 | [10, 11, 16, 20], 16 | [23, 30, 34, 50] 17 | ] 18 | Given target = 3, return 1 ( 1 corresponds to true ) 19 | 20 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 21 | */ 22 | import java.util.*; 23 | public class Search2D{ 24 | public int searchMatrix(ArrayList> A, int B) { 25 | } 26 | public static void main(String[] args){ 27 | ArrayList> A = new ArrayList>(); 28 | int k = 0; 29 | for(int i = 0; i < 3; i++){ 30 | A.add(new ArrayList()); 31 | for(int j = 0; j < 3; j++){ 32 | A.get(i).set(j, k); 33 | k++; 34 | } 35 | } 36 | int B = Integer.parseInt(args[0]); 37 | System.out.println(searchMatrix(A,B); 38 | } 39 | } -------------------------------------------------------------------------------- /BinarySearch/Books.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/Books.class -------------------------------------------------------------------------------- /BinarySearch/FindTargetCount.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/FindTargetCount.class -------------------------------------------------------------------------------- /BinarySearch/FindTargetCount.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | import java.util.*; 5 | public class FindTargetCount { 6 | public int findCount(final List a, int b) { 7 | 8 | int firstIndex = BinarySearch(a, b, true); 9 | if(firstIndex == -1) 10 | return 0; 11 | int lastIndex = BinarySearch(a, b, false); 12 | return lastIndex - firstIndex + 1; 13 | } 14 | 15 | public int BinarySearch(List a, int b, boolean searchFirst) { 16 | int low = 0; 17 | int high = a.size() -1; 18 | int result = -1; 19 | while(low <= high) { 20 | int mid = (low + high) / 2; 21 | if(a.get(mid) == b) { 22 | result= mid; 23 | if(searchFirst) 24 | high = mid - 1; 25 | else 26 | low = mid + 1; 27 | } 28 | else if(b < a.get(mid)) 29 | high = mid - 1; 30 | else 31 | low = mid + 1; 32 | } 33 | return result; 34 | } 35 | public static void main(String[] args) { 36 | List a = new ArrayList(); 37 | a.add(5); 38 | a.add(7); 39 | a.add(7); 40 | a.add(8); 41 | a.add(8); 42 | a.add(10); 43 | 44 | System.out.println(findCount(a, 8)); 45 | } 46 | } -------------------------------------------------------------------------------- /BinarySearch/GetMedianOfTwoSortedArrays.java: -------------------------------------------------------------------------------- 1 | /* 2 | * http://articles.leetcode.com/2011/03/median-of-two-sorted-arrays.html 3 | */ 4 | 5 | public class GetMedianOfTwoSortedArrays{ 6 | } -------------------------------------------------------------------------------- /BinarySearch/InsertPos.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/InsertPos.class -------------------------------------------------------------------------------- /BinarySearch/InsertPos.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 3 | * 4 | You may assume no duplicates in the array. 5 | 6 | Here are few examples. 7 | 8 | [1,3,5,6], 5 ? 2 9 | [1,3,5,6], 2 ? 1 10 | [1,3,5,6], 7 ? 4 11 | [1,3,5,6], 0 ? 0 12 | */ 13 | import java.util.*; 14 | public class InsertPos{ 15 | public static int searchInsert(ArrayList A, int B) { 16 | if(A == null) return 0; 17 | if(B <= A.get(0)) return 0; 18 | 19 | for(int i = 0; i < A.size()-1; i++){ 20 | if(A.get(i) < B && B <= A.get(i + 1)) 21 | return i + 1; 22 | } 23 | return A.size(); 24 | } 25 | // Efficient Approach 26 | public static int searchInsertBetter(ArrayList A, int B) { 27 | if(A == null || A.size() == 0) return 0; 28 | return searchInsert(A, B, 0, A.size() - 1); 29 | } 30 | 31 | public static int searchInsert(ArrayList A, int B, int start, int end){ 32 | int mid = (start + end )/ 2; 33 | if(B == A.get(mid)) { 34 | return mid; 35 | } 36 | else if(B < A.get(mid)) { 37 | return start < mid ? searchInsert(A,B,start,mid-1):start; 38 | } 39 | else { 40 | return end > mid ? searchInsert(A,B,mid+1,end):(end+1); 41 | } 42 | } 43 | 44 | public static void main(String[] args){ 45 | int B = Integer.parseInt(args[0]); 46 | ArrayList A = new ArrayList(); 47 | A.add(1); 48 | A.add(3); 49 | A.add(5); 50 | A.add(6); 51 | 52 | System.out.println(searchInsertBetter(A, B)); 53 | 54 | } 55 | } -------------------------------------------------------------------------------- /BinarySearch/MedianArray.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/MedianArray.class -------------------------------------------------------------------------------- /BinarySearch/MedianArray.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/MedianArray.java -------------------------------------------------------------------------------- /BinarySearch/MedianOfTwoSortedArrays.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/MedianOfTwoSortedArrays.class -------------------------------------------------------------------------------- /BinarySearch/Paint.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/Paint.class -------------------------------------------------------------------------------- /BinarySearch/Paint.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/Paint.java -------------------------------------------------------------------------------- /BinarySearch/PaintKBoards.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/PaintKBoards.class -------------------------------------------------------------------------------- /BinarySearch/PaintKBoards.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/PaintKBoards.java -------------------------------------------------------------------------------- /BinarySearch/Pow.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/Pow.class -------------------------------------------------------------------------------- /BinarySearch/PowerUsingBinarySearch.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/PowerUsingBinarySearch.class -------------------------------------------------------------------------------- /BinarySearch/PowerUsingBinarySearch.java: -------------------------------------------------------------------------------- 1 | public class PowerUsingBinarySearch{ 2 | 3 | public static int pow(int x, int n, int d) { 4 | long a = x; 5 | long result = 1; 6 | while(n > 0) { 7 | System.out.println("For n = " + n); 8 | if(n % 2 == 1){ 9 | result = result * a; 10 | result = result % d; 11 | } 12 | 13 | a = a * a; 14 | a = a % d; 15 | n = n >> 1; 16 | System.out.println("\t result = " + result + " \n \t a = " + a); 17 | } 18 | result = (result + d) % d; 19 | return (int)result; 20 | } 21 | public static void main(String[] args){ 22 | int x = Integer.parseInt(args[0]); 23 | int n = Integer.parseInt(args[1]); 24 | int d = Integer.parseInt(args[2]); 25 | int result = pow(x, n, d); 26 | System.out.println(result); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /BinarySearch/Search2D.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/Search2D.class -------------------------------------------------------------------------------- /BinarySearch/SearchRange.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/SearchRange.class -------------------------------------------------------------------------------- /BinarySearch/SearchRange.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/SearchRange.java -------------------------------------------------------------------------------- /BinarySearch/SearchRotated.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/SearchRotated.class -------------------------------------------------------------------------------- /BinarySearch/Sqrt.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BinarySearch/Sqrt.class -------------------------------------------------------------------------------- /BinarySearch/Sqrt.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Implement int sqrt(int x). 3 | 4 | Compute and return the square root of x. 5 | 6 | If x is not a perfect square, return floor(sqrt(x)) 7 | */ 8 | import java.util.*; 9 | public class Sqrt{ 10 | public static int sqrt(int A) { 11 | long i = 0; 12 | long j = A / 2 + 1; 13 | while(i <= j){ 14 | long mid = (i + j) / 2; 15 | if(mid * mid == A) 16 | return (int)mid; 17 | if(mid * mid < A) 18 | i = mid + 1; 19 | else 20 | j = mid - 1; 21 | } 22 | return (int)j; 23 | } 24 | public static void main(String[] args){ 25 | int A = Integer.parseInt(args[0]); 26 | System.out.println(sqrt(A)); 27 | } 28 | } -------------------------------------------------------------------------------- /BitManipulation/Divide.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BitManipulation/Divide.class -------------------------------------------------------------------------------- /BitManipulation/Divide.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BitManipulation/Divide.java -------------------------------------------------------------------------------- /BitManipulation/Num1Bits.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BitManipulation/Num1Bits.class -------------------------------------------------------------------------------- /BitManipulation/Num1Bits.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a function that takes an unsigned integer and returns the number of 1 bits it has. 3 | 4 | Example: 5 | 6 | The 32-bit integer 11 has binary representation 7 | 8 | 00000000000000000000000000001011 9 | so the function should return 3. 10 | 11 | Note that since Java does not have unsigned int, use long for Java 12 | */ 13 | public class Num1Bits{ 14 | public static int numSetBits(long a) { 15 | int count = 0; 16 | while(a > 0){ 17 | if(a % 2 == 1) 18 | count++; 19 | 20 | a = a/2; 21 | } 22 | return count; 23 | } 24 | public static void main(String[] args){ 25 | long a = 64; 26 | System.out.println(numSetBits(a)); 27 | } 28 | } -------------------------------------------------------------------------------- /BitManipulation/RevBits.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BitManipulation/RevBits.class -------------------------------------------------------------------------------- /BitManipulation/RevBits.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Reverse bits of an 32 bit unsigned integer 3 | 4 | Example 1: 5 | 6 | x = 0, 7 | 8 | 00000000000000000000000000000000 9 | => 00000000000000000000000000000000 10 | return 0 11 | 12 | Example 2: 13 | 14 | x = 3, 15 | 16 | 00000000000000000000000000000011 17 | => 11000000000000000000000000000000 18 | return 3221225472 19 | 20 | Since java does not have unsigned int, use long 21 | */ 22 | public class RevBits{ 23 | public static long reverse(long a) { 24 | long result = 0; 25 | int i = 31; 26 | while(a > 0){ 27 | result += (a % 2) * Math.pow(2, i); 28 | i--; 29 | a = a/2; 30 | } 31 | return result; 32 | } 33 | public static void main(String[] args){ 34 | long a = 4; 35 | System.out.println(reverse(a)); 36 | } 37 | } -------------------------------------------------------------------------------- /BitManipulation/Single.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BitManipulation/Single.class -------------------------------------------------------------------------------- /BitManipulation/Single.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an array of integers, every element appears twice except for one. Find that single one. 3 | 4 | Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 5 | */ 6 | import java.util.*; 7 | public class Single{ 8 | public static int singleNumber(final List a) { 9 | int result = a.get(0); 10 | for(int i = 1; i < a.size(); i++){ 11 | result ^= a.get(i); 12 | } 13 | return result; 14 | } 15 | public static void main(String[] args){ 16 | List a = new ArrayList(); 17 | a.add(1); 18 | a.add(3); 19 | a.add(2); 20 | a.add(2); 21 | a.add(1); 22 | 23 | System.out.println(singleNumber(a)); 24 | } 25 | } -------------------------------------------------------------------------------- /BitManipulation/Single2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/BitManipulation/Single2.class -------------------------------------------------------------------------------- /CheckPrime.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/CheckPrime.class -------------------------------------------------------------------------------- /CheckPrime.java: -------------------------------------------------------------------------------- 1 | public class CheckPrime { 2 | public static int isPrime(int A) { 3 | if (A == 1) { 4 | return 0; 5 | } 6 | System.out.println(Math.sqrt(A)); 7 | for(int i = 2; i <= Math.sqrt(A); i++){ 8 | if(A % i == 0){ 9 | return 0; 10 | } 11 | } 12 | return 1; 13 | } 14 | public static void main(String[] args) { 15 | System.out.println(isPrime(Integer.parseInt(args[0]))); 16 | } 17 | } -------------------------------------------------------------------------------- /CountFrequencies.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/CountFrequencies.class -------------------------------------------------------------------------------- /CountFrequencies.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an unsorted array of n integers which can contain integers from 1 to n. 3 | * Some elements can be repeated multiple times and some other elements can be absent from the array. 4 | * Count frequency of all elements that are present and print the missing elements. 5 | */ 6 | public class CountFrequencies{ 7 | //O(N) space 8 | public static int[] bruteForceCount(int[] A){ 9 | int[] B = new int[A.length]; 10 | for(int i = 0; i < A.length; i++){ 11 | B[A[i]-1]++; 12 | } 13 | return B; 14 | } 15 | 16 | public static int[] bestCount(int[] A){ 17 | int i =0; 18 | while(i < A.length){ 19 | if(A[i] <= 0){ 20 | i++; 21 | continue; 22 | } 23 | 24 | int elementIndex = A[i] - 1; 25 | 26 | if(A[elementIndex] > 0){ 27 | A[i] = A[elementIndex]; 28 | A[elementIndex] = -1; 29 | } 30 | else{ 31 | A[elementIndex]--; 32 | A[i] = 0; 33 | i++; 34 | } 35 | } 36 | for(int j = 0; j < A.length; j++) 37 | A[j] = Math.abs(A[j]); 38 | return A; 39 | } 40 | 41 | public static void main(String[] args){ 42 | int[] A = {2,3,3,2,5}; 43 | A = bestCount(A); 44 | for(int i = 0; i < A.length; i++){ 45 | System.out.printf("%d -> %d \n",i + 1, A[i]); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /DynamicProgramming/Adjacent.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/Adjacent.class -------------------------------------------------------------------------------- /DynamicProgramming/Arrange2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | import java.util.*; 5 | public class Arrange2 { 6 | 7 | } -------------------------------------------------------------------------------- /DynamicProgramming/AvgSet.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/AvgSet.class -------------------------------------------------------------------------------- /DynamicProgramming/Books.java: -------------------------------------------------------------------------------- 1 | /* 2 | * N number of books are given. 3 | The ith book has Pi number of pages. 4 | You have to allocate books to M number of students so that maximum number of pages alloted to a student is minimum. A book will be allocated to exactly one student. Each student has to be allocated atleast one book. 5 | 6 | NOTE: Return -1 if a valid assignment is not possible, and allotment should be in contiguous order. 7 | 8 | Input: 9 | List of Books M number of students 10 | 11 | Your function should return an integer corresponding to the minimum number. 12 | 13 | Example: 14 | 15 | P : [12, 34, 67, 90] 16 | M : 2 17 | 18 | Output : 113 19 | 20 | There are 2 number of students. Books can be distributed in following fashion : 21 | 1) [12] and [34, 67, 90] 22 | Max number of pages is allocated to student 2 with 34 + 67 + 90 = 191 pages 23 | 2) [12, 34] and [67, 90] 24 | Max number of pages is allocated to student 2 with 67 + 90 = 157 pages 25 | 3) [12, 34, 67] and [90] 26 | Max number of pages is allocated to student 1 with 12 + 34 + 67 = 113 pages 27 | 28 | Of the 3 cases, Option 3 has the minimum pages = 113. 29 | 30 | */ 31 | import java.util.*; 32 | public class Books{ 33 | public static int books(ArrayList a, int b) { 34 | int minPages = Integer.MAX_VALUE; 35 | int[] max = new int[b]; 36 | 37 | for(int i = 0; i < b; i++){ 38 | max[i] += a.get(j); 39 | } 40 | } 41 | public static void main(String[] args){ 42 | ArrayList a = new ArrayList(); 43 | a.add(12); 44 | a.add(34); 45 | a.add(67); 46 | a.add(90); 47 | int b = Integer.parseInt(args[0]); 48 | System.out.println(books(a, b)); 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /DynamicProgramming/CoinChange2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/CoinChange2.class -------------------------------------------------------------------------------- /DynamicProgramming/DataStructure.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/DataStructure.class -------------------------------------------------------------------------------- /DynamicProgramming/DataStructure.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class DataStructure { 3 | ArrayList a; 4 | HashMap map; 5 | //Difference between using hashmap and hashtable 6 | public DataStructure() { 7 | a = new ArrayList(); 8 | map = new HashMap(); 9 | } 10 | public void add(int t){ 11 | if(map.get(t) != null) return; 12 | a.add(t); 13 | map.put(t, a.size()-1); 14 | } 15 | public void remove(int t){ 16 | if(map.get(t) != null) { 17 | int index = map.get(t); 18 | map.remove(t); 19 | 20 | int size = a.size(); 21 | Integer last = a.get(size - 1); 22 | Collections.swap(a, index, size - 1); 23 | a.remove(size - 1); 24 | map.put(last, index); 25 | } 26 | } 27 | 28 | 29 | public int getRandom(){ 30 | Random rand = new Random(); 31 | int index = rand.nextInt(a.size()); 32 | return a.get(index); 33 | } 34 | public Integer search(int t){ 35 | return map.get(t); 36 | } 37 | public void display(){ 38 | System.out.println(a); 39 | } 40 | public static void main(String[] args){ 41 | DataStructure ds = new DataStructure(); 42 | ds.add(10); 43 | ds.add(20); 44 | ds.add(30); 45 | ds.add(40); 46 | ds.display(); 47 | System.out.println(ds.search(30)); 48 | ds.display(); 49 | ds.remove(20); 50 | System.out.print("After removing 20"); 51 | ds.display(); 52 | ds.add(50); 53 | System.out.print("After adding 50"); 54 | ds.display(); 55 | System.out.println(ds.search(50)); 56 | System.out.println("Get random " + ds.getRandom()); 57 | } 58 | } -------------------------------------------------------------------------------- /DynamicProgramming/InterLeave.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/InterLeave.class -------------------------------------------------------------------------------- /DynamicProgramming/Jump1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/Jump1.class -------------------------------------------------------------------------------- /DynamicProgramming/Jump2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/Jump2.class -------------------------------------------------------------------------------- /DynamicProgramming/Jump2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | * 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Your goal is to reach the last index in the minimum number of jumps. 7 | 8 | Example : 9 | Given array A = [2,3,1,1,4] 10 | 11 | The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) 12 | 13 | If it is not possible to reach the end index, return -1. 14 | */ 15 | import java.util.*; 16 | public class Jump2{ 17 | public static int jump(ArrayList a) { 18 | if(a == null || a.size() == 0) 19 | return 0; 20 | int steps = 0; 21 | int max =0; 22 | int next =0; 23 | for(int i =0; i < a.size() - 1 && next < a.size() -1; i++){ 24 | max = Math.max(max, i + a.get(i)); 25 | if(i == next){//ready to jump 26 | if(max == next) 27 | return -1;//unreachable 28 | next = max; 29 | steps++; 30 | } 31 | } 32 | return steps; 33 | } 34 | public static void main(String[] args){ 35 | ArrayList a = new ArrayList(); 36 | a.add(2); 37 | a.add(3); 38 | a.add(1); 39 | a.add(1); 40 | a.add(4); 41 | System.out.println(jump(a)); 42 | } 43 | } -------------------------------------------------------------------------------- /DynamicProgramming/LongestIncreasingSequence.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/LongestIncreasingSequence.class -------------------------------------------------------------------------------- /DynamicProgramming/LongestIncreasingSequence.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/LongestIncreasingSequence.java -------------------------------------------------------------------------------- /DynamicProgramming/MaxPathTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a binary tree, find the maximum path sum. 3 | * 4 | The path may start and end at any node in the tree. 5 | 6 | Example : 7 | 8 | Given the below binary tree, 9 | 10 | 1 11 | / \ 12 | 2 3 13 | Return 6. 14 | */ 15 | import java.util.*; 16 | public class MaxPathTree{ 17 | public int maxPathSum(TreeNode a) { 18 | 19 | int max[] = new int[1]; 20 | max[0] = Integer.MIN_VALUE; 21 | calculateSum(a, max); 22 | return max[0]; 23 | 24 | } 25 | 26 | public int calculateSum(TreeNode node, int[] max){ 27 | if(node == null) 28 | return 0; 29 | 30 | int left = calculateSum(node.left,max); 31 | int right = calculateSum(node.right, max); 32 | 33 | int current = Math.max(node.val, Math.max(node.val + left, node.val + right)); 34 | max[0] = Math.max(max[0], Math.max(current, left + node.val + right)); 35 | return current; 36 | } 37 | public static void main(String[] args){ 38 | } 39 | } -------------------------------------------------------------------------------- /DynamicProgramming/MaxProd.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/MaxProd.class -------------------------------------------------------------------------------- /DynamicProgramming/MaxProd.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class MaxProd{ 3 | public static int maxProduct(final List a) { 4 | int minEndingHere = 1; 5 | int maxEndingHere = 1; 6 | int maxProductSoFar = 1; 7 | 8 | for(int i = 0; i < a.size(); i++){ 9 | //System.out.println("for a.get(i): " + a.get(i)); 10 | if(a.get(i) > 0){ 11 | maxEndingHere = maxEndingHere * a.get(i); 12 | minEndingHere = Math.min(minEndingHere*a.get(i), 1); 13 | } 14 | else if(a.get(i) == 0){ 15 | minEndingHere = 1; 16 | maxEndingHere = 1; 17 | } 18 | else { 19 | int temp = maxEndingHere; 20 | maxEndingHere = Math.max(minEndingHere*a.get(i),1); 21 | minEndingHere = temp * a.get(i); 22 | } 23 | maxProductSoFar = Math.max(maxProductSoFar, maxEndingHere); 24 | // System.out.println("\t MaxEndingHere = " + maxEndingHere + "\n \t minEndingHere = " + minEndingHere); 25 | } 26 | return maxProductSoFar > 1 ? maxProductSoFar : 0; 27 | } 28 | public static void main(String[] args){ 29 | List a = new ArrayList(); 30 | a.add(2); 31 | a.add(3); 32 | a.add(-2); 33 | a.add(4); 34 | System.out.println(maxProduct(a)); 35 | } 36 | } -------------------------------------------------------------------------------- /DynamicProgramming/MaxRectangle.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/MaxRectangle.class -------------------------------------------------------------------------------- /DynamicProgramming/MaxRectangle.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/MaxRectangle.java -------------------------------------------------------------------------------- /DynamicProgramming/MinimumPath.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/MinimumPath.class -------------------------------------------------------------------------------- /DynamicProgramming/Palin2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/Palin2.class -------------------------------------------------------------------------------- /DynamicProgramming/Stairs.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/Stairs.class -------------------------------------------------------------------------------- /DynamicProgramming/Stocks1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/Stocks1.class -------------------------------------------------------------------------------- /DynamicProgramming/Stocks1.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Say you have an array for which the ith element is the price of a given stock on day i. 3 | * 4 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 5 | 6 | Example : 7 | 8 | Input : [1 2] 9 | Return : 1 10 | 11 | http://www.programcreek.com/2014/02/leetcode-best-time-to-buy-and-sell-stock-java/ 12 | */ 13 | import java.util.*; 14 | public class Stocks1{ 15 | public static int maxProfit(final List a) { 16 | if(a == null || a.size() == 0) 17 | return 0; 18 | int profit = 0; 19 | 20 | int minElement = Integer.MAX_VALUE; 21 | for(int i = 0; i < a.size(); i++){ 22 | System.out.println("For i : " + i); 23 | profit = Math.max(profit, a.get(i) - minElement); 24 | System.out.println("\t Profit = " + profit); 25 | minElement = Math.min(minElement, a.get(i)); 26 | System.out.println("\t minElement : " + minElement); 27 | } 28 | return profit; 29 | 30 | } 31 | public static void main(String[] args){ 32 | List a = new ArrayList(); 33 | a.add(1); 34 | a.add(2); 35 | System.out.println(maxProfit(a)); 36 | } 37 | } -------------------------------------------------------------------------------- /DynamicProgramming/Stocks2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/Stocks2.class -------------------------------------------------------------------------------- /DynamicProgramming/Stocks2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Say you have an array for which the ith element is the price of a given stock on day i. 3 | * 4 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 5 | 6 | Example : 7 | 8 | Input : [1 2 3] 9 | Return : 2 10 | */ 11 | import java.util.*; 12 | public class Stocks2{ 13 | public static int maxProfit(final List a) { 14 | int profit = 0; 15 | for(int i = 1; i < a.size(); i++){ 16 | int diff = a.get(i) - a.get(i-1); 17 | if(diff > 0) 18 | profit += diff; 19 | 20 | } 21 | return profit; 22 | } 23 | public static void main(String[] args){ 24 | List a = new ArrayList(); 25 | a.add(1); 26 | a.add(2); 27 | a.add(3); 28 | System.out.println(maxProfit(a)); 29 | } 30 | } -------------------------------------------------------------------------------- /DynamicProgramming/Stocks3.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/Stocks3.class -------------------------------------------------------------------------------- /DynamicProgramming/Stocks3.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Say you have an array for which the ith element is the price of a given stock on day i. 3 | * 4 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 5 | 6 | Note: 7 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 8 | 9 | Example : 10 | 11 | Input : [1 2 1 2] 12 | Output : 2 13 | 14 | Explanation : 15 | Day 1 : Buy 16 | Day 2 : Sell 17 | Day 3 : Buy 18 | Day 4 : Sell 19 | 20 | http://www.programcreek.com/2014/02/leetcode-best-time-to-buy-and-sell-stock-iii-java/ 21 | */ 22 | import java.util.*; 23 | public class Stocks3{ 24 | public static int maxProfit(final List a) { 25 | if(a == null || a.size() == 0) 26 | return 0; 27 | 28 | int profit = 0; 29 | 30 | int[] left = new int[a.size()]; 31 | int[] right = new int[a.size()]; 32 | 33 | left[0] = 0; 34 | int min = a.get(0); 35 | for(int i = 1; i < a.size(); i++){ 36 | min = Math.min(min, a.get(i)); 37 | left[i] = Math.max(left[i-1], a.get(i) - min); 38 | } 39 | 40 | right[a.size()-1] = 0; 41 | int max = a.get(a.size()-1); 42 | for(int i = a.size() - 2; i >= 0; i--){ 43 | max = Math.max(max, a.get(i)); 44 | right[i] = Math.max(right[i+1], max- a.get(i)); 45 | } 46 | 47 | for(int i =0; i < a.size(); i++) 48 | profit = Math.max(profit, left[i] + right[i]); 49 | return profit; 50 | } 51 | public static void main(String[] args){ 52 | List a = new ArrayList(); 53 | a.add(1); 54 | a.add(4); 55 | a.add(5); 56 | a.add(7); 57 | a.add(6); 58 | a.add(3); 59 | a.add(2); 60 | a.add(9); 61 | 62 | System.out.println(maxProfit(a)); 63 | } 64 | } -------------------------------------------------------------------------------- /DynamicProgramming/StocksK.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/StocksK.class -------------------------------------------------------------------------------- /DynamicProgramming/StocksK.java: -------------------------------------------------------------------------------- 1 | /* 2 | * http://www.programcreek.com/2014/03/leetcode-best-time-to-buy-and-sell-stock-iv-java/ 3 | */ 4 | import java.util.*; 5 | public class StocksK{ 6 | public static int maxProfit(int k, final List a) { 7 | if(a == null || a.size() == 0 || k < 0) 8 | return 0; 9 | int[] local = new int[k+1]; 10 | int[] global = new int[k+1]; 11 | 12 | for(int i = 0; i < a.size() - 1; i++){ 13 | int diff = a.get(i+1) - a.get(i); 14 | for(int j = k; j >= 1; j--){ 15 | local[j] = Math.max(global[j-1] + Math.max(diff, 0), local[j] + diff); 16 | global[j] = Math.max(local[j], global[j]); 17 | } 18 | } 19 | for(int i =0; i < local.length; i++) 20 | System.out.print(local[i]+" "); 21 | 22 | System.out.println(); 23 | for(int i =0; i < global.length; i++) 24 | System.out.print(global[i]+" "); 25 | 26 | System.out.println(); 27 | return global[k]; 28 | 29 | } 30 | public static void main(String[] args){ 31 | List a = new ArrayList(); 32 | a.add(1); 33 | a.add(4); 34 | a.add(5); 35 | a.add(7); 36 | a.add(6); 37 | a.add(3); 38 | a.add(2); 39 | a.add(9); 40 | int k = Integer.parseInt(args[0]); 41 | System.out.println(maxProfit(k, a)); 42 | } 43 | } -------------------------------------------------------------------------------- /DynamicProgramming/UniqueTrees.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/UniqueTrees.class -------------------------------------------------------------------------------- /DynamicProgramming/UniqueTrees.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/UniqueTrees.java -------------------------------------------------------------------------------- /DynamicProgramming/WordBreak1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/WordBreak1.class -------------------------------------------------------------------------------- /DynamicProgramming/WordBreak1.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. 3 | 4 | For example, given 5 | s = "leetcode", 6 | dict = ["leet", "code"]. 7 | 8 | Return true because "leetcode" can be segmented as "leet code". 9 | 10 | http://www.programcreek.com/2012/12/leetcode-solution-word-break/ 11 | */ 12 | import java.util.*; 13 | public class WordBreak1{ 14 | public static boolean wordbreak(String s, ArrayList dictionary){ 15 | boolean[] t = new boolean[s.length() + 1]; 16 | t[0] = true; 17 | 18 | for(int i = 0; i < s.length(); i++){ 19 | if(!t[i]) 20 | continue; 21 | for(String word : dictionary){ 22 | int length = word.length(); 23 | int end = i + length; 24 | if(end > s.length()) 25 | continue; 26 | if(t[end]) 27 | continue; 28 | if(s.substring(i, end).equals(word)) 29 | t[end] = true; 30 | } 31 | } 32 | return t[s.length()]; 33 | } 34 | 35 | public static void main(String[] args){ 36 | ArrayList b = new ArrayList(); 37 | b.add("cat"); 38 | b.add("cats"); 39 | b.add("and"); 40 | b.add("sand"); 41 | b.add("dog"); 42 | String a = "catsanddog"; 43 | System.out.println("List is : " + b); 44 | System.out.println("String is : " + a); 45 | 46 | if(!wordbreak(a, b)) 47 | System.out.print("Not " ); 48 | System.out.println("Breakable"); 49 | 50 | } 51 | } -------------------------------------------------------------------------------- /DynamicProgramming/WordBreak2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/DynamicProgramming/WordBreak2.class -------------------------------------------------------------------------------- /Excel1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Excel1.class -------------------------------------------------------------------------------- /Excel1.java: -------------------------------------------------------------------------------- 1 | public class Excel1{ 2 | public static int titleToNumber(String A){ 3 | if(A == null || A.length() == 0){ 4 | return 0; 5 | } 6 | int result = 0; 7 | int i = A.length() - 1; 8 | int t = 0; 9 | while(i >= 0) { 10 | char c = A.charAt(i); 11 | result = result +(int)Math.pow(26, t) * (c - 'A' + 1); 12 | //System.out.println(result); 13 | t++; 14 | i--; 15 | } 16 | return result; 17 | } 18 | 19 | public static String titleToString(int N){ 20 | StringBuffer sb = new StringBuffer(); 21 | if(N <= 0) 22 | return null; 23 | int i = 0; 24 | while(N > 0) { 25 | int rem = N % 26; 26 | if(rem == 0) { 27 | rem = 26; 28 | } 29 | sb.insert(0, (char)('A' + rem -1)); 30 | if(rem == 26) 31 | N = N/26 - 1; 32 | else 33 | N = N/26; 34 | } 35 | return sb.toString(); 36 | } 37 | 38 | public static String convertToTitle(int n) { 39 | StringBuilder ans= new StringBuilder(); 40 | while(n > 0) { 41 | ans.insert(0, (char)((n - 1) % 26 + 'A')); 42 | n = (n - 1) / 26; 43 | } 44 | return ans.toString(); 45 | } 46 | 47 | public static void main(String[] args){ 48 | System.out.println(titleToNumber(args[0])); 49 | System.out.println(titleToString(titleToNumber(args[0]))); 50 | System.out.println(convertToTitle(titleToNumber(args[0]))); 51 | } 52 | } -------------------------------------------------------------------------------- /Factorial.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Factorial.class -------------------------------------------------------------------------------- /Factorial.java: -------------------------------------------------------------------------------- 1 | public class Factorial{ 2 | public static long factorial(int N){ 3 | if(N == 0) 4 | return 1; 5 | return N * factorial(N-1); 6 | } 7 | 8 | public static int findTrailingZeros(int n) 9 | { 10 | // Initialize result 11 | int count = 0; 12 | 13 | // Keep dividing n by powers of 5 and update count 14 | while(n > 0){ 15 | count += n/5; 16 | n = n/5; 17 | } 18 | 19 | return count; 20 | } 21 | public static void main(String[] args){ 22 | int N = Integer.parseInt(args[0]); 23 | System.out.println("Factorial of " + N + " is " + factorial(N)); 24 | System.out.println(findTrailingZeros(N)); 25 | 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /FirstMissingPositiveInteger.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/FirstMissingPositiveInteger.class -------------------------------------------------------------------------------- /GCD.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/GCD.class -------------------------------------------------------------------------------- /GCD.java: -------------------------------------------------------------------------------- 1 | public class GCD{ 2 | public static int gcd(int p, int q){ 3 | if(q == 0) return p; 4 | int r = p % q; 5 | return gcd(q, r); 6 | } 7 | 8 | public static void main(String[] args){ 9 | int p = Integer.parseInt(args[0]); 10 | int q = Integer.parseInt(args[1]); 11 | System.out.println(gcd(p, q)); 12 | } 13 | } -------------------------------------------------------------------------------- /Graphs/Black.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Graphs/Black.class -------------------------------------------------------------------------------- /Graphs/CloneGraph.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. 3 | */ 4 | import java.util.*; 5 | public class CloneGraph{ 6 | HashMap map; 7 | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { 8 | map=new HashMap(); 9 | return auxCloneGraph(node); 10 | } 11 | public UndirectedGraphNode auxCloneGraph(UndirectedGraphNode node){ 12 | if(node==null) 13 | return node; 14 | if(map.containsKey(node)){ 15 | return map.get(node); 16 | } 17 | UndirectedGraphNode clone=new UndirectedGraphNode(node.label); 18 | map.put(node,clone); 19 | for(UndirectedGraphNode neighbor : node.neighbors){ 20 | clone.neighbors.add(auxCloneGraph(neighbor)); 21 | } 22 | return clone; 23 | } 24 | public static void main(String[] args){ 25 | } 26 | } -------------------------------------------------------------------------------- /Graphs/DirectedEdge.java: -------------------------------------------------------------------------------- 1 | public class DirectedEdge 2 | { 3 | private final int v; // edge source 4 | private final int w; // edge target 5 | private final int weight; // edge weight 6 | public DirectedEdge(int v, int w, int weight) 7 | { 8 | this.v = v; 9 | this.w = w; 10 | this.weight = weight; 11 | } 12 | public int weight() 13 | { return weight; } 14 | public int from() 15 | { return v; } 16 | public int to() 17 | { return w; } 18 | public String toString() 19 | { return String.format("%d->%d %.2f", v, w, weight); } 20 | } -------------------------------------------------------------------------------- /Graphs/EdgeWeightedDigraph.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class EdgeWeightedDigraph 3 | { 4 | private final int V; // number of vertices 5 | private int E; // number of edges 6 | private Bag[] adj; // adjacency lists 7 | public EdgeWeightedDigraph(int V) 8 | { 9 | this.V = V; 10 | this.E = 0; 11 | adj = (Bag[]) new Bag[V]; 12 | for (int v = 0; v < V; v++) 13 | adj[v] = new Bag(); 14 | } 15 | public EdgeWeightedDigraph(ArrayList A, ArrayList B) { 16 | for(int i =0; i < A.size(); i++) { 17 | int v = i; 18 | int w = A.get(i); 19 | DirectedEdge e = new DirectedEdge(v, w, 0); 20 | addEdge(e); 21 | } 22 | for(int i =0; i < B.size(); i++) { 23 | int v = i; 24 | int w = B.get(i); 25 | DirectedEdge e = new DirectedEdge(v, w, 1); 26 | addEdge(e); 27 | } 28 | } 29 | public int V() { return V; } 30 | public int E() { return E; } 31 | public void addEdge(DirectedEdge e) 32 | { 33 | adj[e.from()].add(e); 34 | E++; 35 | } 36 | public Iterable adj(int v) 37 | { return adj[v]; } 38 | public Iterable edges() 39 | { 40 | Bag bag = new Bag(); 41 | for (int v = 0; v < V; v++) 42 | for (DirectedEdge e : adj[v]) 43 | bag.add(e); 44 | return bag; 45 | } 46 | } -------------------------------------------------------------------------------- /Graphs/FibSum.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Graphs/FibSum.class -------------------------------------------------------------------------------- /Graphs/FibSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * How many minimum numbers from fibonacci series are required such that sum of numbers should be equal to a given Number N ? 3 | Note : repetition of number is allowed. 4 | 5 | Example: 6 | 7 | N = 4 8 | Fibonacci numbers : 1 1 2 3 5 .... so on 9 | here 2 + 2 = 4 10 | so minimum numbers will be 2 11 | */ 12 | import java.util.*; 13 | public class FibSum { 14 | int[] fib; 15 | public static int fibsum(int n) { 16 | if(n <= 2) 17 | return 2; 18 | int a = 1; 19 | int b = 1; 20 | int c = 1; 21 | 22 | ArrayList fibNums = new ArrayList(); 23 | fibNums.add(1); 24 | fibNums.add(1); 25 | while(true){ 26 | c = a + b; 27 | if(c <= n) 28 | fibNums.add(c); 29 | else 30 | break; 31 | 32 | a = b; 33 | b = c; 34 | } 35 | 36 | System.out.println("Fibnums : " + fibNums); 37 | int count = 0; 38 | int num = n; 39 | int index = fibNums.size() - 1; 40 | while(num > 0){ 41 | System.out.printf("For index = %d and num = %d \n ", index, num); 42 | int fib = fibNums.get(index); 43 | System.out.println("\t fib = " + fib); 44 | if(num >= fib){ 45 | 46 | count += (num/fib); 47 | System.out.printf("\t count += (num/fib); is %d \n", count); 48 | num %= fib; 49 | System.out.println("\t num %= fib is " + num); 50 | 51 | } 52 | index--; 53 | } 54 | return count; 55 | } 56 | 57 | public static void main(String[] args){ 58 | int a = Integer.parseInt(args[0]); 59 | System.out.println(fibsum(a)); 60 | 61 | } 62 | } -------------------------------------------------------------------------------- /Graphs/FiniteAutomata.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | import java.util.*; 5 | public class FiniteAutomata { 6 | ArrayList result; 7 | 8 | public void printAllKLength(char[] set, int n){ 9 | result = new ArrayList(); 10 | printAllKLengthRec(set, "", set.length, n); 11 | } 12 | public void printAllKLengthRec(char[] set, String prefix, int length, int n){ 13 | if(n == 0) { 14 | result.add(prefix); 15 | return; 16 | } 17 | for(int i = 0; i < length; i++) { 18 | String newPrefix = prefix + set[i]; 19 | printAllKLengthRec(set, newPrefix, length, n-1); 20 | } 21 | } 22 | public int automata(ArrayList A, ArrayList B, ArrayList C, int D, int N) { 23 | int count = 0; 24 | String a = "01"; 25 | printAllKLength(a.toCharArray(), N); 26 | 27 | for(String s : result) { 28 | char[] arr = s.toCharArray(); 29 | if(arr[0] == A.get(D) 30 | for(int i = 0; i < arr.length; i++) { 31 | if(arr[i] == ) 32 | } 33 | } 34 | 35 | 36 | return count; 37 | } 38 | } -------------------------------------------------------------------------------- /Graphs/KnightEfficient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | public class KnightEfficient { 5 | public class Vertex { 6 | int x; 7 | int y; 8 | public Vertex(int x, int y){ 9 | this.x = x; 10 | this.y = y; 11 | } 12 | } 13 | public class Graph { 14 | Vertex[] vertices = new Vertex[]; 15 | private Bag[] adj; 16 | public Graph(int x1, int y1){ 17 | 18 | 19 | } 20 | public void addEdge(Vertex v, Vertex w){ 21 | } 22 | 23 | 24 | } 25 | 26 | 27 | public int knight(int N, int M, int x1, int y1, int x2, int y2) { 28 | 29 | } 30 | 31 | public static void main(String[] args){ 32 | } 33 | } -------------------------------------------------------------------------------- /Graphs/LevelOrder.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Graphs/LevelOrder.java -------------------------------------------------------------------------------- /Graphs/StepNum.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Graphs/StepNum.class -------------------------------------------------------------------------------- /Graphs/Surrounding.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Graphs/Surrounding.class -------------------------------------------------------------------------------- /Graphs/WordLadder1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Graphs/WordLadder1.class -------------------------------------------------------------------------------- /Graphs/WordLadder2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Graphs/WordLadder2.class -------------------------------------------------------------------------------- /Graphs/WordNode.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Graphs/WordNode.class -------------------------------------------------------------------------------- /Graphs/WordNode.java: -------------------------------------------------------------------------------- 1 | public class WordNode{ 2 | String word; 3 | int numSteps; 4 | WordNode pre; 5 | public WordNode(String word, int numSteps, WordNode pre){ 6 | this.word = word; 7 | this.numSteps = numSteps; 8 | this.pre = pre; 9 | } 10 | public WordNode(String word, int numSteps){ 11 | this.word = word; 12 | this.numSteps = numSteps; 13 | } 14 | } -------------------------------------------------------------------------------- /Graphs/WordSearch.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Graphs/WordSearch.class -------------------------------------------------------------------------------- /Graphs/WordSearch1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Graphs/WordSearch1.class -------------------------------------------------------------------------------- /GreedyAlgorithms/Bulbs.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/GreedyAlgorithms/Bulbs.class -------------------------------------------------------------------------------- /GreedyAlgorithms/Bulbs.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | import java.util.*; 5 | public class Bulbs { 6 | public static int bulbs(ArrayList A) { 7 | // int[] dp = new int[A.size()]; 8 | 9 | // for(int i = 0; i < A.size(); i++) { 10 | // dp[i] = A.get(i); 11 | // } 12 | int switchCount = 0; 13 | for(int i = 0; i < A.size(); i++) { 14 | if(A.get(i) == 0){ 15 | switchCount++; 16 | for(int j = i; j < A.size(); j++) { 17 | if(A.get(j) == 0){ 18 | A.set(j, 1); 19 | } 20 | else { 21 | A.set(j, 0); 22 | } 23 | } 24 | } 25 | } 26 | return switchCount; 27 | } 28 | 29 | public static void main(String[] args) { 30 | ArrayList A = new ArrayList(); 31 | A.add(0); 32 | A.add(0); 33 | A.add(0); 34 | A.add(0); 35 | System.out.println(bulbs(A)); 36 | 37 | System.out.println(Integer.parseInt(args[0])); 38 | } 39 | } -------------------------------------------------------------------------------- /GreedyAlgorithms/Candy.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/GreedyAlgorithms/Candy.class -------------------------------------------------------------------------------- /GreedyAlgorithms/Gas.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/GreedyAlgorithms/Gas.class -------------------------------------------------------------------------------- /GreedyAlgorithms/Gas.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/GreedyAlgorithms/Gas.java -------------------------------------------------------------------------------- /GreedyAlgorithms/Majority.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/GreedyAlgorithms/Majority.class -------------------------------------------------------------------------------- /GreedyAlgorithms/MaxProduct3.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/GreedyAlgorithms/MaxProduct3.class -------------------------------------------------------------------------------- /GreedyAlgorithms/MaxProduct3.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an array of integers, return the highest product possible by multiplying 3 numbers from the array 3 | 4 | Input: 5 | 6 | array of integers e.g {1, 2, 3} 7 | NOTE: Solution will fit in a 32-bit signed integer 8 | Example: 9 | 10 | [0, -1, 3, 100, 70, 50] 11 | 12 | => 70*50*100 = 350000 13 | 14 | */ 15 | import java.util.*; 16 | 17 | public class MaxProduct3{ 18 | public static int maxp3(ArrayList a) { 19 | Collections.sort(a); 20 | int n = a.size(); 21 | System.out.println(a); 22 | return Math.max((a.get(n-1) * a.get(n-2) * a.get(n-3)), 23 | (a.get(n-1) * a.get(0) * a.get(1))); 24 | } 25 | public static void main(String[] args){ 26 | ArrayList a = new ArrayList(); 27 | a.add(0); 28 | a.add(-1); 29 | a.add(3); 30 | a.add(100); 31 | a.add(-70); 32 | a.add(-50); 33 | 34 | System.out.println(maxp3(a)); 35 | } 36 | } -------------------------------------------------------------------------------- /GreedyAlgorithms/Mice$Mices.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/GreedyAlgorithms/Mice$Mices.class -------------------------------------------------------------------------------- /GreedyAlgorithms/Mice.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/GreedyAlgorithms/Mice.class -------------------------------------------------------------------------------- /GreedyAlgorithms/Seats.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/GreedyAlgorithms/Seats.class -------------------------------------------------------------------------------- /Hashing/Anagrams.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/Anagrams.class -------------------------------------------------------------------------------- /Hashing/ColorFull.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/ColorFull.class -------------------------------------------------------------------------------- /Hashing/CopyList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * A linked list is given such that each node contains an additional random pointer which could point to any node in the list or NULL. 3 | 4 | Return a deep copy of the list. 5 | 6 | Example 7 | 8 | Given list 9 | 10 | 1 -> 2 -> 3 11 | with random pointers going from 12 | 13 | 1 -> 3 14 | 2 -> 1 15 | 3 -> 1 16 | You should return a deep copy of the list. The returned answer should not contain the same node as the original list, but a copy of them. The pointers in the returned list should not link to any node in the original input list. 17 | */ 18 | import java.util.*; 19 | public class CopyList{ 20 | public static RandomListNode copyRandomList(RandomListNode head) { 21 | if(head == null) return null; 22 | HashMap map = new HashMap(); 23 | RandomListNode newHead = new RandomListNode(head.label); 24 | RandomListNode p = head; 25 | RandomListNode q = newHead; 26 | 27 | map.put(head, newHead); 28 | p = p.next; 29 | while(p != null){ 30 | RandomListNode temp = new RandomListNode(p.label); 31 | map.put(p, temp); 32 | q.next = temp; 33 | q = temp; 34 | p = p.next; 35 | } 36 | p = head; 37 | q = newHead; 38 | while(p != null){ 39 | if(p.randome != null) 40 | q.randome = map.get(p.random); 41 | else 42 | q.random = null; 43 | p = p.next; 44 | q = q.next; 45 | } 46 | return newHead; 47 | } 48 | public static void main(String[] args){ 49 | } 50 | } -------------------------------------------------------------------------------- /Hashing/Equal$Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/Equal$Pair.class -------------------------------------------------------------------------------- /Hashing/Equal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/Equal.class -------------------------------------------------------------------------------- /Hashing/FourSum.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/FourSum.class -------------------------------------------------------------------------------- /Hashing/Fraction.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/Fraction.class -------------------------------------------------------------------------------- /Hashing/LSZero.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/LSZero.class -------------------------------------------------------------------------------- /Hashing/Points.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/Points.class -------------------------------------------------------------------------------- /Hashing/RandomListNode.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list with a random pointer. */ 3 | 4 | public class RandomListNode { 5 | int label; 6 | RandomListNode next, random; 7 | RandomListNode(int x) { this.label = x; } 8 | }; 9 | -------------------------------------------------------------------------------- /Hashing/RepeatString.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/RepeatString.class -------------------------------------------------------------------------------- /Hashing/SubString.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/SubString.class -------------------------------------------------------------------------------- /Hashing/SubstringCount.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/SubstringCount.class -------------------------------------------------------------------------------- /Hashing/SubstringCount.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class SubstringCount { 3 | public static void count(String s, int length){ 4 | HashMap map = new HashMap<>(); 5 | for(int i = 0; i <= s.length() - length; i++){ 6 | String temp = s.substring(i, i + length); 7 | System.out.println("Substring: " + temp); 8 | if(map.containsKey(temp)) { 9 | map.put(temp, map.get(temp) + 1); 10 | } 11 | else { 12 | map.put(temp, 1); 13 | } 14 | } 15 | 16 | for(Map.Entry entry : map.entrySet()) { 17 | System.out.println(entry.getKey() + ": " + entry.getValue()); 18 | } 19 | } 20 | public static void main(String[] args) { 21 | String s = "ABCGRETCABCG"; 22 | int length = 3; 23 | count(s, 3); 24 | } 25 | } -------------------------------------------------------------------------------- /Hashing/TwoSum$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/TwoSum$Node.class -------------------------------------------------------------------------------- /Hashing/TwoSum.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/TwoSum.class -------------------------------------------------------------------------------- /Hashing/ValidSudoku.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/ValidSudoku.class -------------------------------------------------------------------------------- /Hashing/ValidSudoku.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Hashing/ValidSudoku.java -------------------------------------------------------------------------------- /HeapsAndMaps/LRU.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/HeapsAndMaps/LRU.class -------------------------------------------------------------------------------- /HeapsAndMaps/LRU.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/HeapsAndMaps/LRU.java -------------------------------------------------------------------------------- /HeapsAndMaps/ListNode.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * */ 4 | class ListNode { 5 | public int val; 6 | public ListNode next; 7 | ListNode(int x) { val = x; next = null; } 8 | } 9 | -------------------------------------------------------------------------------- /HeapsAndMaps/MergeKList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Merge k sorted linked lists and return it as one sorted list. 3 | * 4 | Example : 5 | 6 | 1 -> 10 -> 20 7 | 4 -> 11 -> 13 8 | 3 -> 8 -> 9 9 | will result in 10 | 11 | 1 -> 3 -> 4 -> 8 -> 9 -> 10 -> 11 -> 13 -> 20 12 | * 13 | */ 14 | import java.util.*; 15 | public class MergeKList{ 16 | public static ListNode mergeKLists(ArrayList a) { 17 | if(a.size() == 0) 18 | return null; 19 | PriorityQueue q = new PriorityQueue(a.size(), new Comparator(){ 20 | @Override 21 | public int compare(ListNode a, ListNode b){ 22 | if(a.val > b.val) 23 | return 1; 24 | else if(a.val < b.val) 25 | return -1; 26 | else 27 | return 0; 28 | } 29 | }); 30 | //Add first node of each list to the queue 31 | for(ListNode node : a){ 32 | if(node != null) 33 | q.add(node); 34 | } 35 | 36 | ListNode head = new ListNode(0); 37 | ListNode p = head; 38 | while(q.size() > 0){ 39 | ListNode temp = q.poll(); // removes the first / head from queue 40 | p.next = temp; 41 | if(temp.next != null) 42 | q.add(temp.next); 43 | p = p.next; 44 | } 45 | return head.next; 46 | 47 | } 48 | public static void main(String[] args){ 49 | ArrayList a = new ArrayList(); 50 | 51 | } 52 | } -------------------------------------------------------------------------------- /HeapsAndMaps/Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/HeapsAndMaps/Node.class -------------------------------------------------------------------------------- /HeapsAndMaps/Node.java: -------------------------------------------------------------------------------- 1 | public class Node{ 2 | int key; 3 | int value; 4 | Node pre; 5 | Node next; 6 | public Node(int key, int value){ 7 | this.key = key; 8 | this.value = value; 9 | } 10 | } -------------------------------------------------------------------------------- /LargestNumber.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/LargestNumber.class -------------------------------------------------------------------------------- /LargestNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class LargestNumber implements Comparator { 3 | // For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. 4 | public String largestNumber(final List A) { 5 | List B = A; 6 | Collections.sort(B, this); 7 | String ans = ""; 8 | for(int i=B.size()-1;i>=0;i--) 9 | ans = ans+Integer.toString(B.get(i)); 10 | return ans; 11 | } 12 | public int compare(Integer a,Integer b){ 13 | String as = Integer.toString(a); 14 | String bs = Integer.toString(b); 15 | String fe = as+bs; 16 | String se = bs+as; 17 | return (fe.compareTo(se)); 18 | } 19 | public static void main(String[] args) { 20 | List A = new ArrayList(); 21 | A.add(3); 22 | A.add(30); 23 | A.add(34); 24 | A.add(5); 25 | A.add(9); 26 | A.add(0); 27 | A.add(0); 28 | A.add(0); 29 | A.add(0); 30 | A.add(0); 31 | LargestNumber l = new LargestNumber(); 32 | String result = l.largestNumber(A); 33 | int flag = 0; 34 | for(int i = 0; i < result.length(); i++){ 35 | if(result.charAt(i) != '0') 36 | flag = 1; 37 | } 38 | if(flag == 1){ 39 | System.out.println(l.largestNumber(A)); 40 | } 41 | else { 42 | System.out.println("0"); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /LargestPairSum.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/LargestPairSum.class -------------------------------------------------------------------------------- /LargestPairSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an unsorted array, find the largest pair sum in it. For example, the largest pair sum in {12, 34, 10, 6, 40} is 74. 3 | 4 | Difficulty Level: Rookie 5 | Expected Time Complexity: O(n) [Only one traversal of array is allowed] 6 | */ 7 | import java.util.*; 8 | public class LargestPairSum{ 9 | public static int bruteForce(int[] A){ 10 | int max = 0; 11 | for(int i = 0; i < A.length-1; i++){ 12 | for(int j = i+1; j < A.length; j++){ 13 | if(max < (A[i]+A[j])) 14 | max = A[i] + A[j]; 15 | } 16 | } 17 | return max; 18 | } 19 | public static int sortSolution(int[] A){ 20 | Arrays.sort(A); 21 | return A[A.length-1] + A[A.length-2]; 22 | } 23 | public static int bestNSolution(int[] A){ 24 | int first = Math.max(A[0], A[1]); 25 | int second = Math.min(A[0], A[1]); 26 | 27 | for(int i = 2; i < A.length; i++){ 28 | if(A[i] > first){ 29 | second = first; 30 | first = A[i]; 31 | } 32 | else if(A[i] > second && A[i] != first) 33 | second = A[i]; 34 | } 35 | return first + second; 36 | } 37 | 38 | 39 | public static void main(String[] args){ 40 | int[] A = {12, 34, 10, 6, 40}; 41 | System.out.println("bruteForce(A) " + bruteForce(A)); 42 | System.out.println("sortSolution(A) " + sortSolution(A)); 43 | System.out.println("bestNSolution(A) " + bestNSolution(A)); 44 | } 45 | } -------------------------------------------------------------------------------- /LinkedLists/AddNumbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | * You are given two linked lists representing two non-negative numbers. 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. 3 | 4 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 5 | Output: 7 -> 0 -> 8 6 | 7 | 342 + 465 = 807 8 | Make sure there are no trailing zeros in the output list 9 | So, 7 -> 0 -> 8 -> 0 is not a valid response even though the value is still 807. 10 | */ 11 | public class AddNumbers{ 12 | public ListNode addTwoNumbers(ListNode a, ListNode b) { 13 | ListNode head = new ListNode(0); 14 | ListNode c = head; 15 | int carry = 0; 16 | while(a != null && b != null){ 17 | int sum = a.val + b.val + carry; 18 | 19 | c.next = new ListNode(sum % 10); 20 | carry = sum / 10; 21 | 22 | a = a.next; 23 | b = b.next; 24 | c = c.next; 25 | } 26 | while(a != null){ 27 | int sum = a.val + carry; 28 | c.next = new ListNode(sum % 10); 29 | carry = sum / 10; 30 | a = a.next; 31 | c = c.next; 32 | } 33 | 34 | while(b != null){ 35 | int sum = b.val + carry; 36 | c.next = new ListNode(sum % 10); 37 | carry = sum / 10; 38 | b = b.next; 39 | c = c.next; 40 | } 41 | if(carry != 0){ 42 | c.next = new ListNode(carry); 43 | } 44 | return head.next; 45 | 46 | } 47 | public static void main(String[] args){ 48 | 49 | } 50 | } -------------------------------------------------------------------------------- /LinkedLists/ListCycle.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 3 | * 4 | Try solving it using constant additional space. 5 | */ 6 | public class ListCycle{ 7 | public ListNode detectCycle(ListNode a) { 8 | ListNode fast = a; 9 | ListNode slow = a; 10 | 11 | boolean hasCycle = false; 12 | while(fast != null && fast.next != null && slow != null){ 13 | fast = fast.next.next; 14 | slow = slow.next; 15 | if(fast == slow){ 16 | hasCycle = true; 17 | break; 18 | } 19 | } 20 | 21 | if(!hasCycle) return null; 22 | 23 | else{ 24 | fast = a; 25 | while(fast != slow){ 26 | fast = fast.next; 27 | slow = slow.next; 28 | } 29 | return fast; 30 | } 31 | 32 | } 33 | public static void main(String[] args){ 34 | } 35 | } -------------------------------------------------------------------------------- /LinkedLists/ListNode.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | class ListNode { 4 | public int val; 5 | public ListNode next; 6 | ListNode(int x) { 7 | val = x; 8 | next = null; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /LinkedLists/Merge.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | public class Merge{ 5 | public ListNode mergeTwoLists(ListNode a, ListNode b) { 6 | if(a == null && b == null) return null; 7 | if(a == null) return b; 8 | if(b == null) return a; 9 | ListNode head = new ListNode(0); 10 | ListNode p = head; 11 | while(a != null && b != null){ 12 | if(a.val <= b.val){ 13 | p.next = a; 14 | a = a.next; 15 | } 16 | else{ 17 | p.next = b; 18 | b = b.next; 19 | } 20 | p = p.next; 21 | } 22 | if(a != null) p.next = a; 23 | if(b != null) p.next = b; 24 | 25 | return head.next; 26 | } 27 | public static void main(String[] args){ 28 | } 29 | } -------------------------------------------------------------------------------- /LinkedLists/PartitionList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 3 | * 4 | You should preserve the original relative order of the nodes in each of the two partitions. 5 | 6 | For example, 7 | Given 1->4->3->2->5->2 and x = 3, 8 | return 1->2->2->4->3->5. 9 | 10 | 11 | Analysis: 12 | Simple idea but be careful with the operation of pointers. 13 | The idea is: first get the last element and the length of the list (1 while loop) 14 | Then scan the whole list, if current node value < x, then go to the next node. 15 | if current node value >=x, then move this node to the end of the list. 16 | until meet the length of the original list. 17 | 18 | http://www.programcreek.com/2013/02/leetcode-partition-list-java/ 19 | */ 20 | public class PartitionList{ 21 | public ListNode partition(ListNode a, int b) { 22 | if(a == null) return null; 23 | 24 | ListNode fakeHead1 = new ListNode(0); 25 | ListNode fakeHead2 = new ListNode(0); 26 | fakeHead1.next = a; 27 | 28 | ListNode curr = a; 29 | ListNode prev = fakeHead1; 30 | ListNode p2 = fakeHead2; 31 | 32 | while(curr != null){ 33 | if(curr.val < x){ 34 | curr = curr.next; 35 | prev = prev.next; 36 | } 37 | else{ 38 | p2.next = curr; 39 | prev.next = curr.next; 40 | 41 | curr = prev.next; 42 | p2 = p2.next; 43 | } 44 | } 45 | p2.next = null; 46 | 47 | prev.next = fakeHead2.next; 48 | return fakeHead.next; 49 | } 50 | public static void main(String[] args){ 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /LinkedLists/RemDuplicatesLink.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a sorted linked list, delete all duplicates such that each element appear only once. 3 | * 4 | For example, 5 | Given 1->1->2, return 1->2. 6 | Given 1->1->2->3->3, return 1->2->3. 7 | */ 8 | public class RemDuplicatesLink{ 9 | public static ListNode deleteDuplicates(ListNode a) { 10 | ListNode cur = a; 11 | ListNode next = a.next; 12 | while(next != null){ 13 | if(cur.val == next.val){ 14 | cur.next = next.next; 15 | next = cur.next; 16 | } 17 | else{ 18 | cur = next; 19 | next = next.next; 20 | } 21 | } 22 | return a; 23 | } 24 | public static void main(String[] args){ 25 | 26 | } 27 | } -------------------------------------------------------------------------------- /LinkedLists/ReorderList.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/LinkedLists/ReorderList.java -------------------------------------------------------------------------------- /LinkedLists/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Reversing Linked list from m to n positions 3 | */ 4 | public class ReverseLinkedList{ 5 | public ListNode reverseBetween(ListNode a, int m, int n) { 6 | if(m == n) return a; 7 | 8 | ListNode prev = null;//track (m-1)th node 9 | ListNode first = new ListNode(0); //First's next points to mth Node 10 | ListNode second = new ListNode(0); //Seconds next points to (n+1)th node 11 | 12 | int i =0; 13 | ListNode p = a; 14 | while(p != null){ 15 | i++; 16 | if(i == m-1) 17 | prev = p; 18 | 19 | if(i == m) 20 | first.next = p; 21 | 22 | if(i == n){ 23 | second.next = p.next; 24 | p.next = null; 25 | } 26 | p = p.next; 27 | } 28 | 29 | if(first.next == null) 30 | return a; 31 | 32 | //Reverse list from m to n 33 | ListNode p1 = first.next; 34 | ListNode p2 = p1.next; 35 | p1.next = second.next; 36 | while(p1 != null && p2 != null){ 37 | ListNode t = p2.next; 38 | p2.next = p1; 39 | p1 = p2; 40 | p2 = t; 41 | 42 | } 43 | if(prev != null) 44 | prev.next = p1; 45 | else 46 | return p1; 47 | return head; 48 | } 49 | } -------------------------------------------------------------------------------- /Linkedin/Complement.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/Complement.class -------------------------------------------------------------------------------- /Linkedin/Complement.java: -------------------------------------------------------------------------------- 1 | public class Complement{ 2 | public static int getIntComplement(int n){ 3 | int complement = 0; 4 | int remainder = 0; 5 | int count = 0; 6 | if(n == 1) 7 | return 0; 8 | if(n == 0) 9 | return 1; 10 | while(n > 1){ 11 | remainder = n % 2; 12 | n = n >> 1; 13 | System.out.println("For n = " + n); 14 | System.out.println("\t remainder = " + remainder); 15 | System.out.println("\t Count = " + count); 16 | if(remainder == 0) 17 | complement = (int)(complement + Math.pow(2, count)); 18 | count++; 19 | System.out.println("\t Complement " + complement); 20 | } 21 | if(n == 0){ 22 | System.out.println("Complement for n = " + n + " is " + complement); 23 | complement = (int)(complement + Math.pow(2, count)); 24 | } 25 | return complement; 26 | } 27 | public static void main(String[] args){ 28 | 29 | System.out.println(getIntComplement(Integer.parseInt(args[0]))); 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /Linkedin/CountCommonCharacters.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/CountCommonCharacters.class -------------------------------------------------------------------------------- /Linkedin/EditDistance.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/EditDistance.class -------------------------------------------------------------------------------- /Linkedin/EvaluateReversePolishNotation.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/EvaluateReversePolishNotation.class -------------------------------------------------------------------------------- /Linkedin/EvaluateReversePolishNotation.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class EvaluateReversePolishNotation { 3 | public static double evaluate(ArrayList expression) { 4 | Stack operands = new Stack(); 5 | String operators = "+*-/"; 6 | for(int i = 0; i < expression.size(); i++){ 7 | String c = expression.get(i); 8 | if(!operators.contains(c)) 9 | operands.push(Double.parseDouble(c)); 10 | else { 11 | String operator = c; 12 | double x = operands.pop(); 13 | double y = operands.pop(); 14 | if(operator == "+") 15 | operands.push(y+x); 16 | else if(operator == "-") 17 | operands.push(y-x); 18 | else if(operator == "*") 19 | operands.push(y*x); 20 | else if(operator == "/"){ 21 | if(x != 0) 22 | operands.push(y/x); 23 | else operands.push(0.0); 24 | } 25 | } 26 | System.out.println("Stack: " + operands); 27 | } 28 | return operands.peek(); 29 | } 30 | public static void main(String[] args){ 31 | ArrayList expression = new ArrayList(); 32 | expression.add("5"); 33 | expression.add("1"); 34 | expression.add("2"); 35 | expression.add("+"); 36 | expression.add("4"); 37 | expression.add("*"); 38 | expression.add("+"); 39 | expression.add("3"); 40 | expression.add("-"); 41 | System.out.println(evaluate(expression)); 42 | } 43 | } -------------------------------------------------------------------------------- /Linkedin/KthSmallestElement.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/KthSmallestElement.class -------------------------------------------------------------------------------- /Linkedin/KthSmallestElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Return the Kth smallest element in an array 3 | */ 4 | public class KthSmallestElement { 5 | public static void swap(int[] a, int i, int j) { 6 | int temp = a[i]; 7 | a[i] = a[j]; 8 | a[j] = temp; 9 | } 10 | public static int partition(int[] a, int lo, int hi){ 11 | int i = lo; 12 | int j = hi + 1; 13 | int v = a[lo]; 14 | while(true) { 15 | while(a[++i] < v) { 16 | if(i == hi) 17 | break; 18 | } 19 | while(v < a[--j]) { 20 | if(j == lo) 21 | break; 22 | } 23 | if(i >= j) 24 | break; 25 | swap(a, i, j); 26 | } 27 | swap(a, lo, j); 28 | return j; 29 | } 30 | 31 | public static int findKthSmallest(int[] a, int k) { 32 | return findKthSmallestHelper(a, k, 0, a.length - 1); 33 | } 34 | public static int findKthSmallestHelper(int[] a, int k, int lo, int hi) { 35 | if(k > 0 && k <= hi - lo + 1) { 36 | int pos = partition(a, lo, hi); 37 | if(pos - lo == k - 1) { 38 | return a[pos]; 39 | } 40 | if(pos - lo > k - 1) { 41 | return findKthSmallestHelper(a, k, lo, pos - 1); 42 | } 43 | else { 44 | return findKthSmallestHelper(a, k - pos + lo - 1, pos + 1, hi); 45 | } 46 | } 47 | return Integer.MAX_VALUE; 48 | } 49 | 50 | public static void main(String[] args) { 51 | int[] a = {1, 2, 3, 4, 5, 8, 10, 11}; 52 | int k = 8; 53 | System.out.println(findKthSmallest(a, k)); 54 | 55 | } 56 | } -------------------------------------------------------------------------------- /Linkedin/LevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | public class LevelOrderTraversal { 4 | public class TreeNode{ 5 | TreeNode left; 6 | TreeNode right; 7 | int val; 8 | } 9 | public ArrayList> traverse(TreeNode a){ 10 | Queue queue = new LinkedList(); 11 | ArrayList> result = new ArrayList>(); 12 | 13 | if(a == null) return result; 14 | 15 | queue.offer(a); 16 | int currentLevel = 1; 17 | int nextLevel = 0; 18 | ArrayList list = new ArrayList(); 19 | while(!queue.isEmpty()){ 20 | TreeNode node = queue.poll(); 21 | currentLevel--; 22 | list.add(node.val); 23 | 24 | if(node.left != null){ 25 | queue.offer(node.left); 26 | nextLevel++; 27 | } 28 | if(node.right != null){ 29 | queue.offer(node.right); 30 | nextLevel++; 31 | } 32 | 33 | if(currentLevel == 0){ 34 | currentLevel = nextLevel; 35 | nextLevel = 0; 36 | result.add(list); 37 | list.clear(); 38 | } 39 | 40 | } 41 | return result; 42 | } 43 | } -------------------------------------------------------------------------------- /Linkedin/ListCycle.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 3 | * 4 | Try solving it using constant additional space. 5 | */ 6 | public class ListCycle{ 7 | public ListNode detectCycle(ListNode a) { 8 | ListNode fast = a; 9 | ListNode slow = a; 10 | 11 | boolean hasCycle = false; 12 | while(fast != null && fast.next != null && slow != null){ 13 | fast = fast.next.next; 14 | slow = slow.next; 15 | if(fast == slow){ 16 | hasCycle = true; 17 | break; 18 | } 19 | } 20 | 21 | if(!hasCycle) return null; 22 | 23 | else{ 24 | fast = a; 25 | while(fast != slow){ 26 | fast = fast.next; 27 | slow = slow.next; 28 | } 29 | return fast; 30 | } 31 | 32 | } 33 | public static void main(String[] args){ 34 | } 35 | } -------------------------------------------------------------------------------- /Linkedin/LongestCommonPrefix.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/LongestCommonPrefix.class -------------------------------------------------------------------------------- /Linkedin/LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a function to find the longest common prefix string amongst an array of strings. 3 | */ 4 | 5 | public class LongestCommonPrefix { 6 | public static String longestCommonPrefix(String[] strs) { 7 | //find the string with minimum length 8 | int minLen = Integer.MAX_VALUE; 9 | for(int i = 0; i < strs.length; i++) { 10 | if(minLen > strs[i].length()) { 11 | minLen = strs[i].length(); 12 | } 13 | } 14 | char prev = '0'; 15 | for(int j = 0; j < minLen; j++) { 16 | for(int i = 0; i < strs.length; i++) { 17 | if(i == 0) { 18 | prev = strs[i].charAt(j); 19 | continue; 20 | } 21 | if(strs[i].charAt(j) != prev) { 22 | return strs[i].substring(0, j); 23 | } 24 | } 25 | } 26 | return strs[0].substring(0, minLen); 27 | } 28 | 29 | public static String longestCommonPrefixEfficient(String[] strs) { 30 | if(strs.length==0) return ""; 31 | String minStr=strs[0]; 32 | 33 | for(int i=1;i 0){ 12 | maxEndingHere = maxEndingHere * a[i]; 13 | minEndingHere = Math.min(1, minEndingHere * a[i]); 14 | } 15 | else if(a[i] == 0){ 16 | maxEndingHere = 1; 17 | minEndingHere = 1; 18 | } 19 | else { 20 | int temp = maxEndingHere; 21 | maxEndingHere = Math.max(minEndingHere * a[i], 1); 22 | minEndingHere = temp * a[i]; 23 | } 24 | maxProductSoFar = Math.max(maxProductSoFar, maxEndingHere); 25 | } 26 | return maxProductSoFar; 27 | } 28 | public static void main(String[] args){ 29 | int[] a = {6, -3, -10, 0, 2}; 30 | System.out.println(maxProduct(a)); 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /Linkedin/MaxSumContiguousArray.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/MaxSumContiguousArray.class -------------------------------------------------------------------------------- /Linkedin/MaxSumContiguousArray.java: -------------------------------------------------------------------------------- 1 | public class MaxSumContiguousArray { 2 | public static int maxSum(int[] a) { 3 | int currentSum = a[0]; 4 | int maxSumSoFar = a[0]; 5 | for(int i =1; i < a.length; i++) { 6 | currentSum = Math.max(currentSum + a[i], a[i]); 7 | maxSumSoFar = Math.max(currentSum, maxSumSoFar); 8 | } 9 | return maxSumSoFar; 10 | } 11 | public static void main(String[] args) { 12 | int[] a = {-2,1,-3,4,-1,2,1,-5,4}; 13 | System.out.println(maxSum(a)); 14 | } 15 | } -------------------------------------------------------------------------------- /Linkedin/MinimumDistance.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/MinimumDistance.class -------------------------------------------------------------------------------- /Linkedin/MinimumWindowSubString.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/MinimumWindowSubString.class -------------------------------------------------------------------------------- /Linkedin/NumberOfTriangles.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/NumberOfTriangles.class -------------------------------------------------------------------------------- /Linkedin/Permutations.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/Permutations.class -------------------------------------------------------------------------------- /Linkedin/Permutations.java: -------------------------------------------------------------------------------- 1 | //Permutations of a given string n! permutations possible 2 | import java.util.*; 3 | public class Permutations { 4 | public ArrayList permute(String s) { 5 | String prefix = ""; 6 | ArrayList result = new ArrayList(); 7 | permuteHelper(prefix, s, result); 8 | System.out.println(result.size()); 9 | return result; 10 | } 11 | 12 | public void permuteHelper(String prefix, String s, ArrayList result) { 13 | System.out.println("For s = " + s); 14 | if(s.length() == 0) { 15 | System.out.println("\t Adding to result " + prefix); 16 | result.add(prefix); 17 | } 18 | 19 | for(int i =0; i < s.length(); i++) { 20 | System.out.println("\t next prefix : "+ prefix + s.charAt(i)); 21 | System.out.println("\t next string : "+s.substring(0, i) + s.substring(i+1, s.length())); 22 | permuteHelper(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, s.length()), result); 23 | } 24 | } 25 | public static void main(String[] args){ 26 | Permutations p = new Permutations(); 27 | System.out.println(p.permute(args[0])); 28 | } 29 | } -------------------------------------------------------------------------------- /Linkedin/PowerFunction.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/PowerFunction.class -------------------------------------------------------------------------------- /Linkedin/PowerFunction.java: -------------------------------------------------------------------------------- 1 | public class PowerFunction { 2 | public static int pow(int a, int b) { 3 | // lets consider a and b are positive 4 | if(b == 0) { 5 | return 1; 6 | } 7 | int result = a; 8 | int increment = a; 9 | for(int i = 1; i < b; i++){ 10 | for(int j = 1; j < a; j++) { 11 | result += increment; 12 | } 13 | increment = result; 14 | } 15 | return result; 16 | } 17 | public static int power(int a, int b){ 18 | int result = 1; 19 | while(b > 0) { 20 | if(b % 2 == 0) { 21 | b = b/2; 22 | a = a*a; 23 | } 24 | else { 25 | b--; 26 | result = result * a; 27 | } 28 | } 29 | return result; 30 | 31 | } 32 | public static void main(String[] args) { 33 | int a = Integer.parseInt(args[0]); 34 | int b = Integer.parseInt(args[1]); 35 | 36 | System.out.println(pow(a, b)); 37 | System.out.println(power(a, b)); 38 | } 39 | } -------------------------------------------------------------------------------- /Linkedin/ReverseWords.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/ReverseWords.class -------------------------------------------------------------------------------- /Linkedin/SequenceNumbers.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/SequenceNumbers.class -------------------------------------------------------------------------------- /Linkedin/SortedAndRotated.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/SortedAndRotated.class -------------------------------------------------------------------------------- /Linkedin/SortedAndRotated.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sorted and rotated array problems 3 | * 3 4 5 1 2 4 | * */ 5 | import java.util.*; 6 | public class SortedAndRotated { 7 | public static int search(int[] a, int key, int start, int end) { 8 | int mid = start + (end - start)/2; 9 | if(a[mid] == key) { 10 | return mid; 11 | } 12 | 13 | // implies left part is sorted 14 | if(a[start] < a[mid]) { 15 | if(key <= a[mid] && key >= a[start]) { 16 | return search(a, key, start, mid-1); 17 | } 18 | return search(a, key, mid + 1, end); 19 | } 20 | 21 | // implies the right part is sorted 22 | if(key >= a[mid] && key <= a[end]) { 23 | return search(a, key, mid + 1, end); 24 | } 25 | return search(a, key, start, mid-1); 26 | } 27 | 28 | 29 | 30 | public static void main(String[] args) { 31 | int [] a = {11, 15, 2, 3, 4, 6, 8, 9, 10}; 32 | int key = 6; 33 | for(int i = 0; i < a.length; i++) { 34 | System.out.print(a[i] + " " ); 35 | } 36 | System.out.println(); 37 | System.out.println(search(a, key, 0, a.length - 1)); 38 | } 39 | } -------------------------------------------------------------------------------- /Linkedin/StrictlyLargerTarget.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/StrictlyLargerTarget.class -------------------------------------------------------------------------------- /Linkedin/StrictlyLargerTarget.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a target and a sorted array, find the element that is strictly larger than the target. 3 | * {a,c,d,e} b output: c 4 | */ 5 | public class StrictlyLargerTarget { 6 | public static int rank(char[] a, char key) { 7 | int n = a.length; 8 | int start = 0; 9 | int end = n -1; 10 | 11 | while(start <= end) { 12 | int mid = start + (end - start)/2; 13 | if(a[mid] == key) { 14 | return mid; 15 | } 16 | if(key < a[mid]) { 17 | end = mid - 1; 18 | } 19 | else if(key > a[mid]) { 20 | start = mid + 1; 21 | } 22 | 23 | } 24 | return start; 25 | } 26 | 27 | //if celing does not exist that is larger number greater than key then it returns 0 28 | public static char ceiling(char[] a, char key) { 29 | int i = rank(a, key); 30 | if(i == a.length) return '0'; 31 | return a[i]; 32 | } 33 | 34 | //returns the number below the given key 35 | public static char floor(char[] a, char key) { 36 | int i = rank(a, key); 37 | if(i < a.length && 38 | key == a[i]) 39 | return a[i]; 40 | return a[i-1]; 41 | } 42 | public static void main(String[] args) { 43 | char[] a = {'b', 'c', 'd', 'e'}; 44 | System.out.println("Ceiling : " + ceiling(a, 'f')); 45 | System.out.println("Floor: " + floor(a, 'f')); 46 | } 47 | } -------------------------------------------------------------------------------- /Linkedin/Uber.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/Uber.class -------------------------------------------------------------------------------- /Linkedin/Uber.java: -------------------------------------------------------------------------------- 1 | public class Uber { 2 | public static double distance(double x1, double y1, double x2, double y2) { 3 | double total = 0.0; 4 | if(Math.ceil(x1) != x1) { 5 | total += Math.ceil(x1) - x1; 6 | } 7 | if(Math.ceil(x2) != x2) { 8 | total += Math.ceil(x2) - x2; 9 | } 10 | 11 | if(Math.ceil(y1) != y1) { 12 | total += Math.ceil(y1) - y1; 13 | } 14 | if(Math.ceil(y2) != y2) { 15 | total += Math.ceil(y2) - y2; 16 | } 17 | 18 | return total; 19 | } 20 | public static void main(String[] args) { 21 | 22 | System.out.println(distance(0.4, 1, 0.9, 3)); 23 | } 24 | } -------------------------------------------------------------------------------- /Linkedin/UnionIntersectLists.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class UnionIntersectLists { 3 | 4 | public static ArrayList union(List a, List b){ 5 | } 6 | public static ArrayList intersect(ArrayList a, ArrayList b){ 7 | } 8 | public static void main(String[] args){ 9 | List a = new ArrayList(); 10 | a.add(5); 11 | a.add(10); 12 | a.add(15); 13 | 14 | List b = new ArrayList(); 15 | a.add(2); 16 | a.add(3); 17 | a.adD(20); 18 | } 19 | } -------------------------------------------------------------------------------- /Linkedin/java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Linkedin/java -------------------------------------------------------------------------------- /Math/AllPrimes.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Math/AllPrimes.class -------------------------------------------------------------------------------- /Math/AllPrimes.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | import java.util.*; 5 | public class AllPrimes { 6 | public static ArrayList sieve(int a) { 7 | ArrayList result = new ArrayList(); 8 | int[] primes = new int[a + 1]; 9 | for(int i = 0; i <= a; i++) { 10 | primes[i] = 1; 11 | } 12 | primes[0] = 0; 13 | primes[1] = 0; 14 | 15 | for(int i = 2; i <= Math.sqrt(a); i++) { 16 | if(primes[i] == 1) { 17 | for(int j = 2; i * j <= a; j++) 18 | primes[i * j] = 0; 19 | } 20 | } 21 | 22 | for(int i = 2; i <= a; i++){ 23 | if(primes[i] == 1) 24 | result.add(i); 25 | } 26 | return result; 27 | } 28 | 29 | public static int countPrimes(int n){ 30 | boolean[] isPrime = new boolean[n+1]; 31 | for(int i = 2; i <= n; i++){ 32 | isPrime[i] = true; 33 | } 34 | 35 | for(int i = 2; i * i <= n; i++){ 36 | if(isPrime[i]){ 37 | for(int j = i; i * j <= n; j++){ 38 | isPrime[i*j] = false; 39 | } 40 | } 41 | } 42 | int count = 0; 43 | for(int i = 2; i <= n; i++){ 44 | if(isPrime[i]) 45 | count++; 46 | } 47 | return count; 48 | } 49 | public static void main(String[] args) { 50 | System.out.println(sieve(Integer.parseInt(args[0]))); 51 | System.out.println(countPrimes(Integer.parseInt(args[0]))); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Math/DecimalToBinary.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Math/DecimalToBinary.class -------------------------------------------------------------------------------- /Math/DecimalToBinary.java: -------------------------------------------------------------------------------- 1 | public class DecimalToBinary { 2 | public static void main(String[] args) { 3 | int a = Integer.parseInt(args[0]); 4 | StringBuilder sb = new StringBuilder(); 5 | while(a > 0) { 6 | sb = sb.insert(0, String.valueOf(a%2)); 7 | a = a/2; 8 | } 9 | System.out.println(sb.toString()); 10 | } 11 | } -------------------------------------------------------------------------------- /Math/Factors.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Math/Factors.class -------------------------------------------------------------------------------- /Math/Factors.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | import java.util.*; 5 | public class Factors { 6 | public static ArrayList allFactors(int a) { 7 | ArrayList result = new ArrayList(); 8 | result.add(1); 9 | result.add(a); 10 | for(int i = 2; i <= a/2; i++) { 11 | if(a % i == 0) { 12 | result.add(1, i); 13 | //result.add(a/i); 14 | } 15 | } 16 | return result; 17 | } 18 | public static ArrayList allFactorsEfficient(int a) { 19 | ArrayList result = new ArrayList(); 20 | for(int i = 1; i <= Math.sqrt(a); i++) { 21 | if(a % i == 0) { 22 | result.add(i); 23 | if(i != Math.sqrt(a)) 24 | result.add(a/i); 25 | } 26 | } 27 | Collections.sort(result); 28 | return result; 29 | } 30 | public static void main(String[] args) { 31 | System.out.println(allFactorsEfficient(Integer.parseInt(args[0]))); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Math/Mode.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Math/Mode.class -------------------------------------------------------------------------------- /Math/Power2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Math/Power2.class -------------------------------------------------------------------------------- /Math/Power2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a positive integer which fits in a 32 bit signed integer, find if it can be expressed as A^P where P > 1 and A > 0. A and P both should be integers. 3 | * 4 | Example 5 | 6 | Input : 4 7 | Output : True 8 | as 2^2 = 4. 9 | */ 10 | import java.util.*; 11 | public class Power2{ 12 | public static boolean isPower(int A) { 13 | int i; 14 | double p; 15 | if(A == 1) 16 | return true; 17 | for(i = 1; i <= Math.sqrt(A); i++){ 18 | p = Math.log(A)/ Math.log(i); 19 | if(p - (int)p < 0.000000001) 20 | return true; 21 | } 22 | return false; 23 | } 24 | 25 | public static boolean isPowerEfficient(int A) { 26 | double x = 2; 27 | double i; 28 | if(A == 1) 29 | return true; 30 | 31 | for(i = 2; i < 33 && x <= (double)(Math.pow(2, 16)); i++){ 32 | if(Math.pow(x, i) == (double)A) 33 | return true; 34 | if(Math.pow(x, i) >= Math.pow(2, 32)){ 35 | i = 1; 36 | x++; 37 | } 38 | } 39 | return false; 40 | } 41 | public static void main(String[] args){ 42 | int A = Integer.parseInt(args[0]); 43 | if(!isPowerEfficient(A)) 44 | System.out.print("False "); 45 | else 46 | System.out.println("True"); 47 | 48 | } 49 | } -------------------------------------------------------------------------------- /Math/PrimeSum.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Math/PrimeSum.class -------------------------------------------------------------------------------- /Math/PrimeSum.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Math/PrimeSum.java -------------------------------------------------------------------------------- /Math/Rank.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Math/Rank.class -------------------------------------------------------------------------------- /Math/Rank2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Math/Rank2.class -------------------------------------------------------------------------------- /Math/Rank2Efficient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | public class Rank2Efficient { 5 | public static int findRank(String A){ 6 | 7 | } 8 | public static void main(String[] args) { 9 | 10 | } 11 | } -------------------------------------------------------------------------------- /Merge.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Merge.class -------------------------------------------------------------------------------- /NearestSmallerNumbers.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/NearestSmallerNumbers.class -------------------------------------------------------------------------------- /NearestSmallerNumbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an array of integers, find the nearest smaller number for every element 3 | * such that the smaller element is on left side 4 | * Input: arr[] = {1, 6, 4, 10, 2, 5} 5 | * Output: {_, 1, 1, 4, 1, 2}First element ('1') has no element on left side. For 6, 6 | * there is only one smaller element on left side '1'. 7 | * For 10, there are three smaller elements on left side (1, 8 | * 6 and 4), nearest among the three elements is 4. 9 | * Input: arr[] = {1, 3, 0, 2, 5} 10 | * Output: {_, 1, _, 0, 2} 11 | */ 12 | public class NearestSmallerNumbers{ 13 | public static void prevSmallerNumber(int[] a){ 14 | Stack s = new Stack(); 15 | int popped = 0; 16 | 17 | for(int i = 0; i < a.length; i++){ 18 | while(!s.isEmpty() && s.peek() >= a[i]){ 19 | popped = s.pop(); 20 | } 21 | if(s.isEmpty()) 22 | System.out.print("_, "); 23 | else 24 | System.out.print(s.peek() + ", "); 25 | s.push(a[i]); 26 | } 27 | } 28 | public static void main(String[] args){ 29 | int[] a = {1, 6, 4, 10, 2, 5}; 30 | prevSmallerNumber(a); 31 | } 32 | } -------------------------------------------------------------------------------- /Palindrome.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Palindrome.class -------------------------------------------------------------------------------- /Palindrome.java: -------------------------------------------------------------------------------- 1 | public class Palindrome{ 2 | public static boolean isPalindrome(int N){ 3 | int number = N; 4 | int reverse = 0; 5 | while(number != 0){ 6 | int remainder = number % 10; 7 | reverse = reverse * 10 + remainder; 8 | number = number/10; 9 | } 10 | return reverse == N; 11 | 12 | } 13 | public static void main(String[] args){ 14 | int N = Integer.parseInt(args[0]); 15 | if(isPalindrome(N)) 16 | System.out.println(N + " is Palindrome"); 17 | else 18 | System.out.println(N + " is not a Palindrome"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Paths.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Paths.class -------------------------------------------------------------------------------- /Paths.java: -------------------------------------------------------------------------------- 1 | public class Paths{ 2 | public static int uniquePaths(int A, int B) { 3 | int[][] matrix = new int[A+10][B+10]; 4 | for(int i = 0; i < A+10; i++){ 5 | for(int j = 0; j< B+10; j++) 6 | matrix[i][j] = 0; 7 | } 8 | matrix[A][B+1] = 1; 9 | for(int r = A; r >= 1; r--){ 10 | for(int c = B; c >= 1; c--){ 11 | matrix[r][c] = matrix[r+1][c]+matrix[r][c+1]; 12 | } 13 | } 14 | return matrix[1][1]; 15 | } 16 | public static void main(String[] args){ 17 | int A = Integer.parseInt(args[0]); 18 | int B = Integer.parseInt(args[1]); 19 | System.out.println(uniquePaths(A,B)); 20 | } 21 | } -------------------------------------------------------------------------------- /PrintMissing.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/PrintMissing.class -------------------------------------------------------------------------------- /PrintMissing.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an array of integers print the missing elements that lie in range 0-99. If there are more than one missing, collate them, otherwise just print the number. 3 | * 4 | Note that the input array may not be sorted and may contain numbers outside the range [0-99], but only this range is to be considered for printing missing elements. 5 | 6 | Examples 7 | 8 | Input: {88, 105, 3, 2, 200, 0, 10} 9 | Output: 1 10 | 4-9 11 | 11-87 12 | 89-99 13 | 14 | 15 | Input: {9, 6, 900, 850, 5, 90, 100, 99} 16 | Output: 0-4 17 | 7-8 18 | 10-89 19 | 91-98 20 | */ 21 | public class PrintMissing{ 22 | public static void printMissingElements(int[] A, int n){ 23 | boolean[] seen = new boolean[n]; 24 | 25 | for(int j = 0; j < A.length; j++){ 26 | if(A[j] < n) 27 | seen[A[j]] = true; 28 | } 29 | int i = 0; 30 | while(i < n){ 31 | if(!seen[i]){ 32 | int j = i+1; 33 | while(j < n && !seen[j]) 34 | j++; 35 | if(i+1 == j) 36 | System.out.printf("%d \n", i); 37 | else 38 | System.out.printf("%d - %d \n", i, j-1); 39 | i = j; 40 | } 41 | else{ 42 | i++; 43 | } 44 | } 45 | } 46 | public static void main(String[] args){ 47 | int n = Integer.parseInt(args[0]); 48 | int[] A = {9, 6, 900, 850, 5, 90, 100, 99}; 49 | printMissingElements(A, n); 50 | } 51 | } -------------------------------------------------------------------------------- /PythagoreanTriplet.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/PythagoreanTriplet.class -------------------------------------------------------------------------------- /Repeat3.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Repeat3.class -------------------------------------------------------------------------------- /Repeat3.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Repeat3.java -------------------------------------------------------------------------------- /ReverseInteger.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/ReverseInteger.class -------------------------------------------------------------------------------- /ReverseInteger.java: -------------------------------------------------------------------------------- 1 | public class ReverseInteger{ 2 | public static int reverse(int A){ 3 | int result = 0; 4 | int N = A; 5 | 6 | while(N != 0){ 7 | if(result != 0 && Integer.MAX_VALUE/result < 10 && Integer.MAX_VALUE/result > -10) 8 | return 0; 9 | result = result * 10 + N % 10; 10 | N = N / 10; 11 | } 12 | 13 | return result; 14 | } 15 | public static void main(String[] args){ 16 | int N = Integer.parseInt(args[0]); 17 | System.out.println("Reverse of " + N + " is " + reverse(N)); 18 | } 19 | } -------------------------------------------------------------------------------- /Stack$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Stack$1.class -------------------------------------------------------------------------------- /Stack$ListIterator.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Stack$ListIterator.class -------------------------------------------------------------------------------- /Stack$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Stack$Node.class -------------------------------------------------------------------------------- /Stack.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Stack.class -------------------------------------------------------------------------------- /StacksAndQueues/Braces.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/StacksAndQueues/Braces.class -------------------------------------------------------------------------------- /StacksAndQueues/EvaluateExpression.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/StacksAndQueues/EvaluateExpression.class -------------------------------------------------------------------------------- /StacksAndQueues/EvaluateExpression.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Evaluate the value of an arithmetic expression in Reverse Polish Notation. 3 | 4 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 5 | 6 | Examples: 7 | 8 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 9 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 10 | */ 11 | import java.util.*; 12 | public class EvaluateExpression{ 13 | public static int evalRPN(ArrayList a) { 14 | Stack operands = new Stack(); 15 | //Stack operators = new Stack(); 16 | String operators = "+*-/"; 17 | for(int i = 0; i < a.size(); i++){ 18 | String c = a.get(i); 19 | 20 | if(!operators.contains(c)) 21 | operands.push(Integer.parseInt(c)); 22 | else { 23 | int x = operands.pop(); 24 | int y = operands.pop(); 25 | String op = c; 26 | if(op == "+") 27 | operands.push(x + y); 28 | else if(op == "-") 29 | operands.push(y - x); 30 | else if(op == "*") 31 | operands.push(y * x); 32 | else if(op == "/") 33 | operands.push(y / x); 34 | } 35 | } 36 | return operands.pop(); 37 | } 38 | public static void main(String[] args){ 39 | ArrayList a = new ArrayList(); 40 | a.add("2"); 41 | a.add("2"); 42 | // a.add("5"); 43 | a.add("/"); 44 | // a.add("+"); 45 | System.out.println(evalRPN(a)); 46 | } 47 | } 48 | //c.compareTo("0") >= 0 || c.compareTo("9") <= 0 -------------------------------------------------------------------------------- /StacksAndQueues/Histogram.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/StacksAndQueues/Histogram.class -------------------------------------------------------------------------------- /StacksAndQueues/Histogram.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/StacksAndQueues/Histogram.java -------------------------------------------------------------------------------- /StacksAndQueues/MinStack.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/StacksAndQueues/MinStack.java -------------------------------------------------------------------------------- /StacksAndQueues/Rain.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/StacksAndQueues/Rain.class -------------------------------------------------------------------------------- /StacksAndQueues/SimplifyPath.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/StacksAndQueues/SimplifyPath.class -------------------------------------------------------------------------------- /StacksAndQueues/SimplifyPath.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/StacksAndQueues/SimplifyPath.java -------------------------------------------------------------------------------- /StacksAndQueues/SlidingMax.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/StacksAndQueues/SlidingMax.class -------------------------------------------------------------------------------- /StacksAndQueues/ValidParanthesis.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/StacksAndQueues/ValidParanthesis.class -------------------------------------------------------------------------------- /Strings/AToI.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/AToI.class -------------------------------------------------------------------------------- /Strings/AToI.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Implement atoi to convert a string to an integer. 3 | * 4 | Note: There might be multiple corner cases here. Clarify all your doubts from the interviewer before coding. 5 | 6 | Questions: 7 | 8 | Q1. Does string contain whitespace characters before the number? 9 | A. Yes 10 | 11 | Q2. Can the string have garbage characters after the number? 12 | A. Yes. Ignore it. 13 | 14 | Q3. If no numeric character is found before encountering garbage characters, what should I do? 15 | A. Return 0. 16 | 17 | Q4. What if the integer overflows? 18 | A. Return INT_MAX if the number is positive, INT_MIN otherwise. 19 | Warning : DO NOT USE LIBRARY FUNCTION FOR ATOI. 20 | If you do, we will disqualify your submission retroactively and give you penalty points. 21 | */ 22 | public class AToI{ 23 | public static int atoi(String a) { 24 | if(a == null || a.length() == 0) 25 | return 0; 26 | a = a.trim(); 27 | double result = 0; 28 | int flag = 0; 29 | int i = 0; 30 | if(a.charAt(0) == '-'){ 31 | flag = 1; 32 | i++; 33 | } 34 | else if(a.charAt(0) == '+') 35 | { 36 | i++; 37 | } 38 | 39 | while(i < a.length() && a.charAt(i) >= '0' && a.charAt(i) <= '9'){ 40 | result = result*10 + (a.charAt(i) - '0'); 41 | System.out.println(result); 42 | 43 | i++; 44 | } 45 | if(flag == 1) 46 | result = -result; 47 | if(result > Integer.MAX_VALUE) 48 | return Integer.MAX_VALUE; 49 | if(result < Integer.MIN_VALUE) 50 | return Integer.MIN_VALUE; 51 | return (int)result; 52 | 53 | } 54 | public static void main(String[] args){ 55 | String a = " 7 U 0 T7165 0128862 089 39 5"; 56 | System.out.println(atoi(a)); 57 | } 58 | } -------------------------------------------------------------------------------- /Strings/AddBinary.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/AddBinary.class -------------------------------------------------------------------------------- /Strings/AddBinary.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/AddBinary.java -------------------------------------------------------------------------------- /Strings/CountSay.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/CountSay.class -------------------------------------------------------------------------------- /Strings/CountSay.java: -------------------------------------------------------------------------------- 1 | /* 2 | * The count-and-say sequence is the sequence of integers beginning as follows: 3 | * 4 | 1, 11, 21, 1211, 111221, ... 5 | 1 is read off as one 1 or 11. 6 | 11 is read off as two 1s or 21. 7 | 8 | 21 is read off as one 2, then one 1 or 1211. 9 | 10 | Given an integer n, generate the nth sequence. 11 | 12 | Note: The sequence of integers will be represented as a string. 13 | 14 | Example: 15 | 16 | if n = 2, 17 | the sequence is 11. 18 | http://www.programcreek.com/2014/03/leetcode-count-and-say-java/ 19 | */ 20 | import java.util.*; 21 | public class CountSay { 22 | public static String countAndSay(int a) { 23 | if(a <= 0) 24 | return null; 25 | String result = "1"; 26 | int i = 1; 27 | 28 | while(i < a){ 29 | StringBuilder sb = new StringBuilder(); 30 | int count = 1; 31 | for(int j = 1; j < result.length(); j++){ 32 | if(result.charAt(j) == result.charAt(j-1)) 33 | count++; 34 | else{ 35 | sb.append(count); 36 | sb.append(result.charAt(j-1)); 37 | count = 1; 38 | } 39 | 40 | } 41 | sb.append(count); 42 | sb.append(result.charAt(result.length() - 1)); 43 | result = sb.toString(); 44 | i++; 45 | System.out.println(result); 46 | } 47 | System.out.println(); 48 | return result; 49 | } 50 | public static void main(String[] args){ 51 | int a = Integer.parseInt(args[0]); 52 | 53 | System.out.println(countAndSay(a)); 54 | } 55 | } -------------------------------------------------------------------------------- /Strings/IPAddress.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/IPAddress.class -------------------------------------------------------------------------------- /Strings/IPAddress.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/IPAddress.java -------------------------------------------------------------------------------- /Strings/Int2Roman.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/Int2Roman.class -------------------------------------------------------------------------------- /Strings/Int2Roman.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an integer, convert it to a roman numeral. 3 | 4 | Input is guaranteed to be within the range from 1 to 3999. 5 | https://tianrunhe.wordpress.com/2012/07/24/convert-an-integer-to-a-roman-numeral-integer-to-roman/ 6 | */ 7 | import java.util.*; 8 | public class Int2Roman{ 9 | private static int[] bases = { 1000, 10 | 900, 11 | 500, 12 | 400, 13 | 100, 14 | 90, 15 | 50, 16 | 40, 17 | 10, 18 | 9, 19 | 5, 20 | 4, 21 | 1}; 22 | private static HashMap map = new HashMap(); 23 | 24 | public static String intToRoman(int a) { 25 | setup(); 26 | String result = ""; 27 | for(int i : bases){ 28 | while(a >= i){ 29 | result += map.get(i); 30 | a -= i; 31 | } 32 | } 33 | return result; 34 | 35 | } 36 | private static void setup(){ 37 | map.put(1, "I"); 38 | map.put(4, "IV"); 39 | map.put(5, "V"); 40 | map.put(9, "IX"); 41 | map.put(10, "X"); 42 | map.put(40, "XL"); 43 | map.put(50, "L"); 44 | map.put(90, "XC"); 45 | map.put(100, "C"); 46 | map.put(400, "CD"); 47 | map.put(500, "D"); 48 | map.put(900, "CM"); 49 | map.put(1000, "M"); 50 | } 51 | public static void main(String[] args){ 52 | int N = Integer.parseInt(args[0]); 53 | System.out.println(intToRoman(N)); 54 | } 55 | } -------------------------------------------------------------------------------- /Strings/LCP.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/LCP.class -------------------------------------------------------------------------------- /Strings/LCP.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/LCP.java -------------------------------------------------------------------------------- /Strings/LenghLast.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/LenghLast.class -------------------------------------------------------------------------------- /Strings/LenghLast.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 3 | 4 | If the last word does not exist, return 0. 5 | 6 | Note: A word is defined as a character sequence consists of non-space characters only. 7 | 8 | Example: 9 | 10 | Given s = "Hello World", 11 | 12 | return 5 as length("World") = 5. 13 | 14 | Please make sure you try to solve this problem without using library functions. Make sure you only traverse the string once. 15 | https://github.com/LuqiPan/LeetCode/blob/master/LengthOfLastWord.java 16 | */ 17 | 18 | public class LenghLast{ 19 | public static int lengthOfLastWord(final String A) { 20 | int lastCount = 0; 21 | int count = 0; 22 | for(int i = 0; i < A.length(); i++){ 23 | if(A.charAt(i) == ' '){ 24 | if(lastCount == 0){ 25 | continue; 26 | } 27 | count = lastCount; 28 | lastCount = 0; 29 | } 30 | else{ 31 | lastCount++; 32 | } 33 | } 34 | return lastCount > 0 ? lastCount : count; 35 | } 36 | public static void main(String[] args){ 37 | String s = "Wordl "; 38 | System.out.println(lengthOfLastWord(s)); 39 | } 40 | } -------------------------------------------------------------------------------- /Strings/LongestPalindrome.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/LongestPalindrome.class -------------------------------------------------------------------------------- /Strings/MaxWeightTransformation.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/MaxWeightTransformation.class -------------------------------------------------------------------------------- /Strings/MaxWeightTransformation.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Maximum weight transformation of a given string 3 | * http://www.geeksforgeeks.org/maximum-weight-transformation-of-a-given-string/ 4 | */ 5 | import java.util.*; 6 | public class MaxWeightTransformation { 7 | public static int getMaxWeight(String s) { 8 | int n = s.length(); 9 | int[] lookup = new int[n]; 10 | for(int i = 0; i < n; i++) 11 | lookup[i] = -1; 12 | 13 | return getMaxRec(s, 0, n, lookup); 14 | } 15 | public static int getMaxRec(String s, int i, int n, int[] lookup) { 16 | if(i >= n) 17 | return 0; 18 | if(lookup[i] != -1) 19 | return lookup[i]; 20 | int ans = 1 + getMaxRec(s, i+1, n, lookup); 21 | if(i + 1 < n) { 22 | if(s.charAt(i) != s.charAt(i+1)){ 23 | ans = Math.max(ans, 4 + getMaxRec(s, i+2, n, lookup)); 24 | } 25 | else { 26 | ans = Math.max(ans, 3 + getMaxRec(s, i+2, n, lookup)); 27 | } 28 | } 29 | lookup[i] = ans; 30 | for(int j = 0; j < n; j++) 31 | System.out.print(lookup[j] + " "); 32 | System.out.println(); 33 | return ans; 34 | } 35 | public static void main(String[] args) { 36 | System.out.println(getMaxWeight(args[0])); 37 | } 38 | } -------------------------------------------------------------------------------- /Strings/Multiply.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/Multiply.class -------------------------------------------------------------------------------- /Strings/Multiply.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/Multiply.java -------------------------------------------------------------------------------- /Strings/Palindrome.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/Palindrome.class -------------------------------------------------------------------------------- /Strings/Palindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 3 | * 4 | Example: 5 | 6 | "A man, a plan, a canal: Panama" is a palindrome. 7 | 8 | "race a car" is not a palindrome. 9 | 10 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 11 | http://www.programcreek.com/2013/01/leetcode-valid-palindrome-java/ 12 | */ 13 | public class Palindrome{ 14 | public static int isPalindrome(String A) { 15 | if(A == null || A.length() == 1) 16 | return 0; 17 | 18 | A = A.replaceAll("[^a-zA-Z0-9]","").toLowerCase(); 19 | int n = A.length(); 20 | System.out.println(A); 21 | for(int i = 0; i < n/2; i++){ 22 | if(A.charAt(i) != A.charAt(n-1-i)) 23 | return 0; 24 | } 25 | return 1; 26 | } 27 | public boolean isAlpha(char a){ 28 | if((a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z')) 29 | return true; 30 | return false; 31 | } 32 | public boolean isNum(char a){ 33 | if(a >= '0' && a <= '9') 34 | return true; 35 | return false; 36 | } 37 | 38 | public boolean isSame(char a, char b){ 39 | if(isNum(a) && isNum(b)){ 40 | return a == b; 41 | } 42 | else if(Character.toLowerCase(a) == Character.toLowerCase(b)){ 43 | return true; 44 | } 45 | else{ 46 | return false; 47 | } 48 | } 49 | public static void main(String[] args){ 50 | String s = "A man, a plan, a canal: Panama"; 51 | System.out.println(isPalindrome(s)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Strings/PerttyJson.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/PerttyJson.class -------------------------------------------------------------------------------- /Strings/PerttyJson.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/PerttyJson.java -------------------------------------------------------------------------------- /Strings/Power.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/Power.class -------------------------------------------------------------------------------- /Strings/Power.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Find if Given number is power of 2 or not. 3 | More specifically, find if given number can be expressed as 2^k where k >= 1. 4 | 5 | Input: 6 | 7 | number length can be more than 64, which mean number can be greater than 2 ^ 64 (out of long long range) 8 | Output: 9 | 10 | return 1 if the number if a power of 2 else return 0 11 | 12 | Example: 13 | 14 | Input : 128 15 | Output : 1 16 | */ 17 | public class Power{ 18 | public static int power(String a) { 19 | int N = Integer.parseInt(a); 20 | if(N % 2 != 0) 21 | return 0; 22 | while(N >= 1){ 23 | N = N/2; 24 | if(N % 2 != 0 && N != 1) 25 | return 0; 26 | } 27 | return 1; 28 | } 29 | public static int powerSolution(String A){ 30 | java.math.BigInteger a = new java.math.BigInteger(A); 31 | if(a.compareTo(java.math.BigInteger.ONE)==0 || a.compareTo(java.math.BigInteger.ZERO)==0)return 0; 32 | for(int i=0;i= 0; i--){ 21 | if(!arr[i].equals("")){ 22 | result.append(arr[i]).append(" "); 23 | } 24 | } 25 | return result.length() == 0 ? "" : result.substring(0, result.length()-1); 26 | 27 | // Stack stack = Stack= 0; i--){ 32 | // if(a.charAt(i) == ' '){ 33 | // stack.push(temp); 34 | // temp = ""; 35 | // } 36 | // else{ 37 | // temp = a.charAt(i) + temp; 38 | // } 39 | // } 40 | // while(!stack.isEmpty()){ 41 | // result += stack.pop() + " "; 42 | // } 43 | // return result; 44 | } 45 | public static void main(String[] args){ 46 | String s = "blue is sky the"; 47 | System.out.println(reverseWords(s)); 48 | } 49 | } -------------------------------------------------------------------------------- /Strings/RomanToInt.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/RomanToInt.class -------------------------------------------------------------------------------- /Strings/RomanToInt.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a roman numeral, convert it to an integer. 3 | * 4 | Input is guaranteed to be within the range from 1 to 3999. 5 | 6 | Read more details about roman numerals here: 7 | 8 | http://en.wikipedia.org/wiki/Roman_numerals ( http://en.wikipedia.org/wiki/Roman_numerals#Reading_Roman_numerals ). 9 | */ 10 | public class RomanToInt{ 11 | public static int c2n(char c){ 12 | switch(c) { 13 | case 'I' : return 1; 14 | case 'V' : return 5; 15 | case 'X' : return 10; 16 | case 'L' : return 50; 17 | case 'C' : return 100; 18 | case 'D' : return 500; 19 | case 'M' : return 1000; 20 | default : return 0; 21 | } 22 | } 23 | public static int romanToInt(String a) { 24 | int result = 0; 25 | for(int i = 0; i < a.length(); i++){ 26 | if(i > 0 && c2n(a.charAt(i)) > c2n(a.charAt(i-1))){ 27 | result += c2n(a.charAt(i)) - 2 * c2n(a.charAt(i-1)); 28 | } 29 | else{ 30 | result += c2n(a.charAt(i)); 31 | } 32 | } 33 | return result; 34 | } 35 | public static void main(String[] args){ 36 | String a = args[0]; 37 | System.out.println(romanToInt(a)); 38 | } 39 | } -------------------------------------------------------------------------------- /Strings/SecondSmallestNumber.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/SecondSmallestNumber.class -------------------------------------------------------------------------------- /Strings/SecondSmallestNumber.java: -------------------------------------------------------------------------------- 1 | public class SecondSmallestNumber{ 2 | public static int secondSmallest(int[] a){ 3 | int s1 = Integer.MAX_VALUE; 4 | int s2 = s1; 5 | for(int i = 0; i < a.length; i++){ 6 | if(a[i] < s1){ 7 | s2 = s1; 8 | s1 = a[i]; 9 | } 10 | else if(a[i] < s2 && a[i] != s1) 11 | s2 = a[i]; 12 | } 13 | return s2; 14 | } 15 | public static void main(String[] args){ 16 | int[] a = {1,3,2,5,6,9}; 17 | System.out.println(secondSmallest(a)); 18 | } 19 | } -------------------------------------------------------------------------------- /Strings/SparseNumber.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/SparseNumber.class -------------------------------------------------------------------------------- /Strings/SparseNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Check if number is sparse or not 3 | * http://www.geeksforgeeks.org/check-if-a-given-number-is-sparse-or-not/ 4 | */ 5 | public class SparseNumber { 6 | public static boolean checkSparse(int n) { 7 | if((n & n/2) > 1) 8 | return false; 9 | return true; 10 | } 11 | public static void main(String[] args) { 12 | int n = Integer.parseInt(args[0]); 13 | if(!checkSparse(n)) 14 | System.out.print("Not "); 15 | System.out.println("Sparse Number"); 16 | } 17 | } -------------------------------------------------------------------------------- /Strings/StrStr.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/StrStr.class -------------------------------------------------------------------------------- /Strings/TestJust.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/TestJust.class -------------------------------------------------------------------------------- /Strings/TestJust.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/TestJust.java -------------------------------------------------------------------------------- /Strings/ValidNumber.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/ValidNumber.class -------------------------------------------------------------------------------- /Strings/Version.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/Version.class -------------------------------------------------------------------------------- /Strings/ZigZag.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Strings/ZigZag.class -------------------------------------------------------------------------------- /Trees/ArrayBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | * 4 | Balanced tree : a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | Example : 6 | 7 | 8 | Given A : [1, 2, 3] 9 | A height balanced BST : 10 | 11 | 2 12 | / \ 13 | 1 3 14 | */ 15 | public class ArrayBST{ 16 | public TreeNode sortedArrayToBST(final List a) { 17 | if(a == null || a.size() == 0) 18 | return null; 19 | return sortedArrayToBST(a, 0, a.size() -1); 20 | } 21 | public TreeNode sortedArrayToBST(final List a, int start, int end) { 22 | if(start > end) 23 | return null; 24 | int mid = (start + end)/2; 25 | TreeNode root = new TreeNode(a.get(mid)); 26 | root.left = sortedArrayToBST(a, start, mid - 1); 27 | root.right = sortedArrayToBST(a, mid+1, end); 28 | return root; 29 | } 30 | public static void main(String[] args){ 31 | } 32 | } -------------------------------------------------------------------------------- /Trees/Balanced.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a binary tree, determine if it is height-balanced. 3 | * 4 | Height-balanced binary tree : is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 6 | 7 | Example : 8 | 9 | Input : 10 | 1 11 | / \ 12 | 2 3 13 | 14 | Return : True or 1 15 | 16 | Input 2 : 17 | 3 18 | / 19 | 2 20 | / 21 | 1 22 | 23 | Return : False or 0 24 | Because for the root node, left subtree has depth 2 and right subtree has depth 0. 25 | Difference = 2 > 1. 26 | */ 27 | import java.util.*; 28 | public class Balanced{ 29 | public int isBalanced(TreeNode a) { 30 | if(a == null) 31 | return 1; 32 | int leftDepth = 0; 33 | int rightDepth = 0; 34 | if(a.left != null) 35 | leftDepth = depth(a.left); 36 | if(a.right != null) 37 | rightDepth = depth(a.right); 38 | if(Math.abs(leftDepth - rightDepth) <= 1 && isBalanced(a.left) == 1 && isBalanced(a.right) == 1) 39 | return 1; 40 | return 0; 41 | 42 | } 43 | public int depth(TreeNode a){ 44 | if(a == null) 45 | return 0; 46 | return 1 + Math.max(depth(a.left), depth(a.right)); 47 | } 48 | public static void main(String[] args){ 49 | } 50 | } -------------------------------------------------------------------------------- /Trees/BinaryTree1.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given inorder and postorder traversal of a tree, construct the binary tree. 3 | * 4 | Note: You may assume that duplicates do not exist in the tree. 5 | Example : 6 | 7 | Input : 8 | Inorder : [2, 1, 3] 9 | Postorder : [2, 3, 1] 10 | 11 | Return : 12 | 1 13 | / \ 14 | 2 3 15 | */ 16 | import java.util.*; 17 | public class BinaryTree1{ 18 | public TreeNode buildTree(ArrayList inorder, ArrayList postorder) { 19 | if(inorder == null || inorder.size() == 0 || 20 | postorder == null || postorder.size() == 0 || 21 | postorder.size() != inorder.size()) 22 | return null; 23 | 24 | 25 | TreeNode root = buildTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() -1); 26 | return root; 27 | } 28 | public TreeNode buildTree(ArrayList inorder, ArrayList postorder, int inStart, int inEnd, int postStart, int postEnd) { 29 | 30 | if(inStart > inEnd || postStart > postEnd) 31 | return null; 32 | 33 | TreeNode node = new TreeNode(postorder.get(postEnd)); 34 | 35 | 36 | int inIndex = 0; 37 | for(int i = inStart; i <= inEnd; i++){ 38 | if(inorder.get(i) == node.val){ 39 | inIndex = i; 40 | break; 41 | } 42 | } 43 | 44 | node.left = buildTree(inorder, postorder, inStart, inIndex - 1, postStart, postStart + inIndex - (inStart +1)); 45 | node.right = buildTree(inorder, postorder, inIndex + 1, inEnd, postStart + inIndex - inStart, postEnd - 1); 46 | return node; 47 | 48 | } 49 | 50 | public static void main(String[] args){ 51 | } 52 | } -------------------------------------------------------------------------------- /Trees/BinaryTree2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given preorder and inorder traversal of a tree, construct the binary tree. 3 | 4 | Note: You may assume that duplicates do not exist in the tree. 5 | Example : 6 | 7 | Input : 8 | Preorder : [1, 2, 3] 9 | Inorder : [2, 1, 3] 10 | 11 | Return : 12 | 1 13 | / \ 14 | 2 3 15 | 16 | */ 17 | import java.util.*; 18 | public class BinaryTree2{ 19 | 20 | public static void main(String[] args){ 21 | } 22 | } -------------------------------------------------------------------------------- /Trees/Cartesian.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an inorder traversal of a cartesian tree, construct the tree. 3 | * 4 | Cartesian tree : is a heap ordered binary tree, where the root is greater than all the elements in the subtree. 5 | Note: You may assume that duplicates do not exist in the tree. 6 | Example : 7 | 8 | Input : [1 2 3] 9 | 10 | Return : 11 | 3 12 | / 13 | 2 14 | / 15 | 1 16 | */ 17 | import java.util.*; 18 | public class Cartesian{ 19 | public TreeNode buildTree(ArrayList a) { 20 | if(a == null || a.size() == 0) 21 | return null; 22 | TreeNode root = buildTree(a, 0, a.size() -1 ); 23 | return root; 24 | } 25 | public TreeNode buildTree(ArrayList a, int start, int end){ 26 | if(start > end) 27 | return null; 28 | 29 | int max = Integer.MIN_VALUE; 30 | int maxIndex = 0; 31 | for(int i = start; i <= end; i++){ 32 | if(max < a.get(i)){ 33 | max = a.get(i); 34 | maxIndex = i; 35 | } 36 | } 37 | 38 | TreeNode root = new TreeNode(max); 39 | 40 | if(start == end) 41 | return root; 42 | root.left = buildTree(a, start, maxIndex - 1); 43 | root.right = buildTree(a, maxIndex + 1, end); 44 | return root; 45 | } 46 | public static void main(String[] args){ 47 | } 48 | } -------------------------------------------------------------------------------- /Trees/Flatten.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a binary tree, flatten it to a linked list in-place. 3 | * 4 | Example : 5 | Given 6 | 7 | 8 | 1 9 | / \ 10 | 2 5 11 | / \ \ 12 | 3 4 6 13 | The flattened tree should look like: 14 | 15 | 1 16 | \ 17 | 2 18 | \ 19 | 3 20 | \ 21 | 4 22 | \ 23 | 5 24 | \ 25 | 6 26 | Note that the left child of all nodes should be NULL. 27 | */ 28 | public class Flatten{ 29 | public TreeNode flatten(TreeNode a) { 30 | TreeNode result = new TreeNode(0); 31 | TreeNode node = result; 32 | result.right = node; 33 | if(a == null) 34 | return null; 35 | 36 | Stack stack = new Stack(); 37 | stack.push(a); 38 | while(!stack.isEmpty()){ 39 | TreeNode popped = stack.pop(); 40 | 41 | node.right = popped; 42 | node.left = null; 43 | node = node.right; 44 | 45 | if(popped.right != null) 46 | stack.push(popped.right); 47 | if(popped.left != null) 48 | stack.push(popped.left); 49 | } 50 | return result.right; 51 | 52 | } 53 | public static void main(String[] args){ 54 | 55 | } 56 | } -------------------------------------------------------------------------------- /Trees/InOrder.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/InOrder.java -------------------------------------------------------------------------------- /Trees/LCA.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/LCA.java -------------------------------------------------------------------------------- /Trees/List2Tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 3 | 4 | A height balanced BST : a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 5 | Example : 6 | 7 | 8 | Given A : 1 -> 2 -> 3 9 | A height balanced BST : 10 | 11 | 2 12 | / \ 13 | 1 3 14 | 15 | */ 16 | import java.util.*; 17 | public class List2Tree{ 18 | public TreeNode sortedListToBST(ListNode a) { 19 | ArrayList list = new ArrayList(); 20 | while(a != null){ 21 | list.add(a.val); 22 | a = a.next; 23 | } 24 | return sortedListToBST(list, 0, list.size()-1); 25 | } 26 | 27 | public TreeNode sortedListToBST(ArrayList a, int start, int end){ 28 | if(start > end) 29 | return null; 30 | int mid = (start + end)/2; 31 | 32 | TreeNode node = new TreeNode(a.get(mid)); 33 | node.left = sortedListToBST(a, start, mid-1); 34 | node.right = sortedListToBST(a, mid+1, end); 35 | return node; 36 | } 37 | public static void main(String[] args){ 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Trees/Majority.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an array of size n, find the majority element. The majority element is the element that appears more than floor(n/2) times. 3 | * 4 | You may assume that the array is non-empty and the majority element always exist in the array. 5 | 6 | Example : 7 | 8 | Input : [2, 1, 2] 9 | Return : 2 which occurs 2 times which is greater than 3/2. 10 | */ 11 | import java.util.*; 12 | public class Majority{ 13 | public int majorityElement(final List a) { 14 | HashMap map = new HashMap(); 15 | int majorElement = Integer.MIN_VALUE; 16 | for(int i : a){ 17 | if(map.containsKey(i)) 18 | map.put(i, map.get(i) + 1); 19 | map.put(i, 1); 20 | } 21 | 22 | Iterator it = map.entrySet.iterator(); 23 | int maxValue = Integer.MIN_VALUE; 24 | while(it.hasNext()){ 25 | Map.Entry pair = (Map.Entry)it.next(); 26 | if(pair.getValue() > maxValue){ 27 | maxValue = pair.getValue(); 28 | majorElement = pair.getKey(); 29 | } 30 | } 31 | return majorElement; 32 | 33 | } 34 | public static void main(String[] args){ 35 | ArrayList a = new ArrayList(); 36 | a.add(2); 37 | a.add(1); 38 | a.add(2); 39 | System.out.println(majorityElement(a)); 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /Trees/MaxDepth.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a binary tree, find its maximum depth. 3 | * 4 | The maximum depth is the number of nodes along the longest path from the root node down to the nearest leaf node. 5 | 6 | NOTE : The path has to end on a leaf node. 7 | Example : 8 | 9 | 1 10 | / 11 | 2 12 | max depth = 2. 13 | */ 14 | import java.util.*; 15 | public class MaxDepth{ 16 | public int maxDepth(TreeNode a) { 17 | if(a == null) 18 | return 0; 19 | return Math.max(maxDepth(a.left) + 1, maxDepth(a.right) + 1); 20 | } 21 | public static void main(String[] args){ 22 | 23 | } 24 | } -------------------------------------------------------------------------------- /Trees/MinDepth.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a binary tree, find its minimum depth. 3 | 4 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | 6 | NOTE : The path has to end on a leaf node. 7 | Example : 8 | 9 | 1 10 | / 11 | 2 12 | min depth = 2. 13 | */ 14 | import java.util.*; 15 | public class MinDepth{ 16 | public int minDepth(TreeNode a) { 17 | if(a == null) 18 | return 0; 19 | if(a.left == null) 20 | return minDepth(a.right) + 1; 21 | if(a.right == null) 22 | return minDepth(a.left) + 1; 23 | return Math.min(minDepth(a.right) + 1, minDepth(a.left) + 1); 24 | 25 | } 26 | public static void main(String[] args){ 27 | } 28 | } -------------------------------------------------------------------------------- /Trees/Order$Person.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/Order$Person.class -------------------------------------------------------------------------------- /Trees/Order.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/Order.class -------------------------------------------------------------------------------- /Trees/Path2.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/Path2.java -------------------------------------------------------------------------------- /Trees/PostOrder.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/PostOrder.java -------------------------------------------------------------------------------- /Trees/PreOrder.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/PreOrder.java -------------------------------------------------------------------------------- /Trees/Prefix.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/Prefix.class -------------------------------------------------------------------------------- /Trees/Recover.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Two elements of a binary search tree (BST) are swapped by mistake. 3 | Tell us the 2 values swapping which the tree will be restored. 4 | 5 | Note: 6 | A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 7 | Example : 8 | 9 | 10 | Input : 11 | 1 12 | / \ 13 | 2 3 14 | 15 | Output : 16 | [1, 2] 17 | 18 | Explanation : Swapping 1 and 2 will change the BST to be 19 | 2 20 | / \ 21 | 1 3 22 | which is a valid BST 23 | */ 24 | import java.util.*; 25 | public class Recover { 26 | ArrayList result = new ArrayList(); 27 | TreeNode pre = null; 28 | TreeNode first = null; 29 | TreeNode second = null; 30 | public ArrayList recoverTree(TreeNode a) { 31 | 32 | recoverTreeHelper(a); 33 | result.add(first.val); 34 | result.add(second.val); 35 | Collections.sort(result); 36 | return result; 37 | } 38 | 39 | public void recoverTreeHelper(TreeNode node) { 40 | if(node == null){ 41 | return; 42 | } 43 | else{ 44 | recoverTreeHelper(node.left); 45 | if(pre == null) 46 | pre = node; 47 | else{ 48 | if(pre.val > node.val){ 49 | if(first == null){ 50 | first = pre; 51 | } 52 | second = node; 53 | } 54 | pre = node; 55 | } 56 | 57 | recoverTreeHelper(node.right); 58 | } 59 | } 60 | public static void main(String[] args){ 61 | } 62 | } -------------------------------------------------------------------------------- /Trees/SameTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given two binary trees, write a function to check if they are equal or not. 3 | * 4 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 5 | 6 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem 7 | 8 | Example : 9 | 10 | Input : 11 | 12 | 1 1 13 | / \ / \ 14 | 2 3 2 3 15 | 16 | Output : 17 | 1 or True 18 | */ 19 | public class SameTree{ 20 | public static int isSameTree(TreeNode a, TreeNode b) { 21 | if(a == null && b == null) 22 | return 1; 23 | else if(a == null || b == null) 24 | return 0; 25 | 26 | if(a.val == b.val && isSameTree(a.left, b.left) == 1 && isSameTree(a.right, b.right) == 1) 27 | return 1; 28 | 29 | return 0; 30 | } 31 | public static void main(String[] args){ 32 | } 33 | } -------------------------------------------------------------------------------- /Trees/SumRootLeaf.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/SumRootLeaf.class -------------------------------------------------------------------------------- /Trees/SumRootLeaf.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 3 | * 4 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 5 | 6 | Find the total sum of all root-to-leaf numbers % 1003. 7 | 8 | Example : 9 | 10 | 1 11 | / \ 12 | 2 3 13 | The root-to-leaf path 1->2 represents the number 12. 14 | The root-to-leaf path 1->3 represents the number 13. 15 | 16 | Return the sum = (12 + 13) % 1003 = 25 % 1003 = 25. 17 | */ 18 | import java.util.*; 19 | public class SumRootLeaf{ 20 | public int sumNumbers(TreeNode a) { 21 | if(a == null) 22 | return 0; 23 | 24 | return (dfs(a, 0)) % 1003; 25 | } 26 | public int dfs(TreeNode node, int num){ 27 | if(node == null) 28 | return 0; 29 | 30 | 31 | 32 | if(node.left == null && node.right == null){ 33 | int newNum = num * 10 + node.val; 34 | return newNum % MOD; 35 | } 36 | num = num * 10 + node.val; 37 | num %= MOD; 38 | int sum = dfs(node.left, num, sum) + dfs(node.right, num, sum); 39 | return sum %1003; 40 | } 41 | public static void main(String[] args){ 42 | 43 | System.out.println(257 % 1003); 44 | } 45 | } -------------------------------------------------------------------------------- /Trees/TreeIterator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. 3 | * 4 | The first call to next() will return the smallest number in BST. Calling next() again will return the next smallest number in the BST, and so on. 5 | 6 | Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 7 | Try to optimize the additional space complexity apart from the amortized time complexity. 8 | */ 9 | public class TreeIterator{ 10 | Stack stack; 11 | public TreeIterator(TreeNode root) { 12 | stack = new Stack(); 13 | while(root != null){ 14 | stack.push(root); 15 | root = root.left; 16 | } 17 | } 18 | 19 | /** @return whether we have a next smallest number */ 20 | public boolean hasNext() { 21 | return !stack.isEmpty(); 22 | } 23 | 24 | /** @return the next smallest number */ 25 | public int next() { 26 | TreeNode node = stack.pop(); 27 | int result = node.val; 28 | if(node.right != null){ 29 | node = node.right; 30 | while(node != null){ 31 | stack.push(node); 32 | node = node.left; 33 | } 34 | } 35 | return result; 36 | 37 | } 38 | 39 | public static void main(String[] args){ 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /Trees/TreeNode.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/TreeNode.class -------------------------------------------------------------------------------- /Trees/TreeNode.java: -------------------------------------------------------------------------------- 1 | 2 | // Definition for binary tree 3 | class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | TreeNode(int x) { val = x; } 8 | } 9 | -------------------------------------------------------------------------------- /Trees/TreeTopView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Problem Statement 3 | 4 | You are given a pointer to the root of a binary tree. Print the top view of the binary tree. 5 | You only have to complete the function. 6 | For example : 7 | 8 | 3 9 | / \ 10 | 5 2 11 | / \ / \ 12 | 1 4 6 7 13 | \ / 14 | 9 8 15 | Top View : 1 -> 5 -> 3 -> 2 -> 7 16 | Input Format 17 | 18 | You are given a function, 19 | 20 | void top_view(node * root) 21 | { 22 | 23 | } 24 | Output Format 25 | 26 | Print the values on a single line separated by space. 27 | 28 | Sample Input 29 | 30 | 3 31 | / \ 32 | 5 2 33 | / \ / \ 34 | 1 4 6 7 35 | \ / 36 | 9 8 37 | Sample Output 38 | 39 | 1 5 3 2 7 40 | Explanation 41 | 42 | 3 43 | / \ 44 | 5 2 45 | / \ / \ 46 | 1 4 6 7 47 | \ / 48 | 9 8 49 | From the top only nodes 1,5,3,2 and 7 will be visible. 50 | */ 51 | public class TreeTopView { 52 | class Node { 53 | int data; 54 | Node left; 55 | Node right; 56 | } 57 | public static void top_view(Node root) 58 | { 59 | if(root != null) { 60 | top_view(root.left, true); 61 | System.out.print(root.data + " "); 62 | top_view(root.right, false); 63 | } 64 | } 65 | 66 | public static void top_view(Node node, boolean goLeft) { 67 | if(node != null) { 68 | if(goLeft) { 69 | top_view(node.left, goLeft); 70 | System.out.print(node.data + " "); 71 | } else { 72 | System.out.print(node.data + " "); 73 | top_view(node.right, goLeft); 74 | } 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /Trees/UnivalTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Unival Tree: A tree in which all the node values are same 3 | */ 4 | public class UnivalTree{ 5 | int count = 0; //to count the unival trees 6 | public boolean unival(TreeNode root){ 7 | if(root == null) 8 | return true; 9 | boolean left = unival(root.left); 10 | boolean right = unival(root.right); 11 | 12 | if(left && right && 13 | (root.left == null || root.left.val == root.val) && 14 | (root.right == null || root.right.val == root.val)){ 15 | count++; 16 | return true; 17 | } 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /Trees/ZigZagTree.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/Trees/ZigZagTree.java -------------------------------------------------------------------------------- /TwoPointers/Array3Pointer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/Array3Pointer.class -------------------------------------------------------------------------------- /TwoPointers/Container.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/Container.class -------------------------------------------------------------------------------- /TwoPointers/Container.java: -------------------------------------------------------------------------------- 1 | /* 2 | * http://www.programcreek.com/2014/03/leetcode-container-with-most-water-java/ 3 | */ 4 | import java.util.*; 5 | public class Container{ 6 | public static int maxArea(ArrayList a) { 7 | if(a.size() <2 || a == null) 8 | return 0; 9 | int max = 0; 10 | int left = 0; 11 | int right = a.size()-1; 12 | while (left < right) { 13 | max = Math.max(max, (right - left) * Math.min(a.get(left), a.get(right))); 14 | if (a.get(left) < a.get(right)) 15 | left++; 16 | else 17 | right--; 18 | } 19 | 20 | return max; 21 | } 22 | public static void main(String[] args){ 23 | ArrayList a = new ArrayList(); 24 | a.add(1); 25 | a.add(2); 26 | a.add(3); 27 | a.add(4); 28 | System.out.println(maxArea(a)); 29 | } 30 | } -------------------------------------------------------------------------------- /TwoPointers/DiffK.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/DiffK.class -------------------------------------------------------------------------------- /TwoPointers/DiffK.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/DiffK.java -------------------------------------------------------------------------------- /TwoPointers/IntersectArr.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/IntersectArr.class -------------------------------------------------------------------------------- /TwoPointers/Longest1sWithKFlips.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/Longest1sWithKFlips.class -------------------------------------------------------------------------------- /TwoPointers/MaxOne.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/MaxOne.class -------------------------------------------------------------------------------- /TwoPointers/Merge.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/Merge.class -------------------------------------------------------------------------------- /TwoPointers/RemElm.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/RemElm.class -------------------------------------------------------------------------------- /TwoPointers/RemElm.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Remove Element 3 | * 4 | Given an array and a value, remove all the instances of that value in the array. 5 | Also return the number of elements left in the array after the operation. 6 | It does not matter what is left beyond the expected length. 7 | 8 | Example: 9 | If array A is [4, 1, 1, 2, 1, 3] 10 | and value elem is 1, 11 | then new length is 3, and A is now [4, 2, 3] 12 | Try to do it in less than linear additional space complexity. 13 | https://gist.github.com/jibojun/8467725 14 | */ 15 | import java.util.*; 16 | public class RemElm{ 17 | public static int removeElement(ArrayList a, int b) { 18 | 19 | System.out.println(a); 20 | int n = a.size(); 21 | if(a == null || n == 0) 22 | return 0; 23 | int start = 0; 24 | for(int i = 0; i < a.size(); i++){ 25 | if(a.get(i) != b){ 26 | a.set(start, a.get(i)); 27 | start++; 28 | } 29 | } 30 | 31 | 32 | System.out.println(a); 33 | return start; 34 | } 35 | 36 | //from solution 37 | public static int removeElementSolution(ArrayList a, int b) { 38 | while(a.contains(b)){ 39 | a.remove(new Integer(b)); 40 | } 41 | for(int i = 0; i < a.size(); i++) 42 | System.out.print(a.get(i) + " "); 43 | return a.size(); 44 | } 45 | public static void main(String[] args){ 46 | ArrayList a = new ArrayList(); 47 | a.add(1); 48 | a.add(2); 49 | a.add(0); 50 | a.add(0); 51 | a.add(2); 52 | a.add(1); 53 | a.add(2); 54 | a.add(0); 55 | a.add(1); 56 | System.out.println(removeElement(a,1)); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /TwoPointers/RemoveDuplicates.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/RemoveDuplicates.class -------------------------------------------------------------------------------- /TwoPointers/RemoveDuplicates2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/RemoveDuplicates2.class -------------------------------------------------------------------------------- /TwoPointers/RemoveDuplicates2.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Remove Duplicates from Sorted Array 4 | * 5 | Given a sorted array, remove the duplicates in place such that each element appear atmost twice and return the new length. 6 | 7 | Do not allocate extra space for another array, you must do this in place with constant memory. 8 | 9 | Note that even though we want you to return the new length, make sure to change the original array as well in place 10 | 11 | For example, 12 | Given input array A = [1,1,1,2], 13 | 14 | Your function should return length = 3, and A is now [1,1,2]. 15 | */ 16 | import java.util.*; 17 | public class RemoveDuplicates2{ 18 | //Working but Time Complexity exceeded 19 | public static int removeDuplicates(ArrayList a) { 20 | Collections.sort(a); 21 | System.out.println("After Sorting: " + a); 22 | int index = 1; 23 | int n = a.size(); 24 | for(int i = 2; i < n; i++){ 25 | if(!a.get(i).equals(a.get(index - 1))){ 26 | index++; 27 | a.set(index, a.get(i)); 28 | //index++; 29 | } 30 | 31 | 32 | } 33 | System.out.println("After removing: " + a); 34 | return index + 1; 35 | 36 | } 37 | public static void main(String[] args){ 38 | ArrayList a = new ArrayList(); 39 | a.add(1); 40 | a.add(2); 41 | a.add(0); 42 | a.add(0); 43 | a.add(2); 44 | a.add(1); 45 | a.add(2); 46 | a.add(0); 47 | a.add(1); 48 | a.add(5000); 49 | a.add(5000); 50 | a.add(5000); 51 | System.out.println(removeDuplicates(a)); 52 | } 53 | } -------------------------------------------------------------------------------- /TwoPointers/SortColor.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/SortColor.class -------------------------------------------------------------------------------- /TwoPointers/ThreeSum.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/ThreeSum.class -------------------------------------------------------------------------------- /TwoPointers/ThreeSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. 3 | Return the sum of the three integers. 4 | You may assume that each input would have exactly one solution. 5 | 6 | Example: 7 | given array S = {-1 2 1 -4}, 8 | and target = 1. 9 | 10 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2) 11 | 12 | http://www.programcreek.com/2013/02/leetcode-3sum-closest-java/ 13 | */ 14 | import java.util.*; 15 | public class ThreeSum{ 16 | public static int threeSumClosest(ArrayList a, int b) { 17 | int min = Integer.MAX_VALUE; 18 | int result = 0; 19 | Collections.sort(a); 20 | 21 | for(int i = 0; i < a.size(); i++){ 22 | int j = i+1; 23 | int k = a.size()-1; 24 | while(j < k){ 25 | int sum = a.get(i) + a.get(j) + a.get(k); 26 | int diff = Math.abs(sum - b); 27 | if(diff == 0) 28 | return sum; // or b 29 | if(diff < min){ 30 | min = diff; 31 | result = sum; 32 | } 33 | if(sum <= b) 34 | j++; 35 | else 36 | k--; 37 | } 38 | } 39 | return result; 40 | } 41 | public static void main(String[] args){ 42 | ArrayList a = new ArrayList(); 43 | a.add(-1); 44 | a.add(2); 45 | a.add(1); 46 | a.add(-4); 47 | System.out.println(threeSumClosest(a, 1)); 48 | } 49 | } -------------------------------------------------------------------------------- /TwoPointers/ThreeSumZero.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/TwoPointers/ThreeSumZero.class -------------------------------------------------------------------------------- /UnionAndIntersection.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nagajyothi/InterviewBit/0d86457f41139d95d0285a7718aee9b53df4aebe/UnionAndIntersection.class --------------------------------------------------------------------------------