From 13bcf057ff84b010fa550b0fe7251f092f07ae27 Mon Sep 17 00:00:00 2001 From: sahil shimpi Date: Sat, 11 Jun 2022 21:39:10 +0530 Subject: [PATCH] commit --- .DS_Store | Bin 10244 -> 10244 bytes Array/ArrayProbs.java/ExtendedNum.class | Bin 0 -> 1325 bytes Array/ArrayProbs.java/Query.class | Bin 269 -> 269 bytes Array/ArrayProbs.java/aread.txt | 27 +++ Array/ArrayProbs.java/array_prob16.java | 47 ++++ Array/ArrayProbs.java/array_prob21$1.class | Bin 1230 -> 1230 bytes Array/ArrayProbs.java/array_prob21.class | Bin 1106 -> 2760 bytes Array/ArrayProbs.java/array_prob21.java | 7 + Array/ArrayProbs.java/array_prob24$1.class | Bin 797 -> 797 bytes Array/ArrayProbs.java/array_prob24.class | Bin 1857 -> 1880 bytes Array/ArrayProbs.java/array_prob24.java | 4 + Array/ArrayProbs.java/array_prob4.java | 21 ++ Array/ArrayProbs.java/array_prob9.java | 2 +- Array/FactorialOfBigNumber.java | 1 - GPP/prob77.java | 62 ++--- Graph/aindex.txt | 4 + Graph/prob27$Coordinate.class | Bin 0 -> 354 bytes Graph/prob27.class | Bin 0 -> 2212 bytes Graph/prob27.java | 182 +++++++++++++++ Graph/prob28_graph$Ele.class | Bin 0 -> 372 bytes Graph/prob28_graph.class | Bin 0 -> 2729 bytes Graph/prob28_graph.java | 214 ++++++++++++++++++ Graph/prob4_graph.java | 20 ++ Graph/prob7_graph.java | 3 +- Greedy/prob10_grdy$1.class | Bin 0 -> 807 bytes Greedy/prob10_grdy$ItemValue.class | Bin 0 -> 508 bytes Greedy/prob10_grdy.class | Bin 0 -> 1608 bytes Greedy/prob10_grdy.java | 62 +++++ Greedy/prob11.class | Bin 0 -> 876 bytes Greedy/prob11.java | 79 +++++++ Greedy/prob12_grdy.class | Bin 0 -> 1422 bytes Greedy/prob12_grdy.java | 192 ++++++++++++++++ Greedy/prob13_grdy.java | 61 +++++ Greedy/prob14_grdy.class | Bin 0 -> 659 bytes Greedy/prob14_grdy.java | 64 ++++++ Greedy/prob15_grdy.class | Bin 0 -> 1284 bytes Greedy/prob15_grdy.java | 88 +++++++ Greedy/prob1_grdy$1.class | Bin 0 -> 732 bytes Greedy/prob1_grdy$Activity.class | Bin 0 -> 364 bytes Greedy/prob1_grdy.class | Bin 0 -> 1527 bytes Greedy/prob1_grdy.java | 57 +++++ Greedy/prob2_grdy.class | Bin 0 -> 1581 bytes Greedy/prob2_grdy.java | 64 ++++++ Greedy/prob3_grdy.class | Bin 0 -> 1681 bytes Greedy/prob3_grdy.java | 67 ++++++ Greedy/prob4_grdy.class | Bin 0 -> 794 bytes Greedy/prob4_grdy.java | 64 ++++++ Greedy/prob5_grdy.java | 51 +++++ Greedy/prob6.java | 55 +++++ Greedy/prob7_grdy.class | Bin 0 -> 977 bytes Greedy/prob7_grdy.java | 54 +++++ Greedy/prob8_grdy.class | Bin 0 -> 2477 bytes Greedy/prob8_grdy.java | 163 +++++++++++++ Greedy/prob9_grdy.java | 60 +++++ Heap&Hashing/aindex.txt | 15 ++ Heap&Hashing/prob10.class | Bin 0 -> 1789 bytes Heap&Hashing/prob10.java | 89 ++++++++ Heap&Hashing/prob11.class | Bin 0 -> 1506 bytes Heap&Hashing/prob11.java | 60 +++++ Heap&Hashing/prob12.class | Bin 0 -> 2043 bytes Heap&Hashing/prob12.java | 83 +++++++ Heap&Hashing/prob13.class | Bin 0 -> 875 bytes Heap&Hashing/prob13.java | 56 +++++ Heap&Hashing/prob14.class | Bin 0 -> 1501 bytes Heap&Hashing/prob14.java | 81 +++++++ Heap&Hashing/prob15.java | 32 +++ Heap&Hashing/prob16.class | Bin 0 -> 1315 bytes Heap&Hashing/prob16.java | 31 +++ Heap&Hashing/prob17.class | Bin 0 -> 1445 bytes Heap&Hashing/prob17.java | 43 ++++ Heap&Hashing/prob3.java | 1 + Heap&Hashing/prob6.java | 1 - Heap&Hashing/prob9.class | Bin 0 -> 821 bytes Heap&Hashing/prob9.java | 87 +++++++ .../SigleLinkedlist/CloneList$Node.class | Bin 0 -> 403 bytes Linkedlist/SigleLinkedlist/CloneList.class | Bin 0 -> 1883 bytes Linkedlist/SigleLinkedlist/CloneList.java | 128 +++++++++++ .../SigleLinkedlist/FlatternList$Node.class | Bin 0 -> 481 bytes Linkedlist/SigleLinkedlist/FlatternList.class | Bin 0 -> 2113 bytes Linkedlist/SigleLinkedlist/FlatternList.java | 154 +++++++++++++ Linkedlist/SigleLinkedlist/index.txt | 112 ++++++++- .../BinarySearch.java | 0 .../LinearSearch.java | 0 Searching&sorting/Node.class | Bin 0 -> 276 bytes Searching&sorting/NodeComparator.class | Bin 0 -> 563 bytes Searching&sorting/aindex.txt | 16 ++ Searching&sorting/prob1.class | Bin 0 -> 1055 bytes Searching&sorting/prob1.java | 17 ++ Searching&sorting/prob10.java | 57 +++++ Searching&sorting/prob11.java | 60 +++++ Searching&sorting/prob12.class | Bin 0 -> 1261 bytes Searching&sorting/prob12.java | 79 +++++++ Searching&sorting/prob13.java | 61 +++++ Searching&sorting/prob14.class | Bin 0 -> 1024 bytes Searching&sorting/prob14.java | 66 ++++++ Searching&sorting/prob15.java | 49 ++++ Searching&sorting/prob16.class | Bin 0 -> 2328 bytes Searching&sorting/prob16.java | 114 ++++++++++ Searching&sorting/prob17.class | Bin 0 -> 662 bytes Searching&sorting/prob17.java | 28 +++ Searching&sorting/prob18.java | 172 ++++++++++++++ Searching&sorting/prob2$pair.class | Bin 0 -> 344 bytes Searching&sorting/prob2.class | Bin 0 -> 1698 bytes Searching&sorting/prob2.java | 123 ++++++++++ Searching&sorting/prob3.class | Bin 0 -> 1888 bytes Searching&sorting/prob3.java | 44 ++++ Searching&sorting/prob4.class | Bin 0 -> 1572 bytes Searching&sorting/prob4.java | 59 +++++ Searching&sorting/prob5.java | 73 ++++++ Searching&sorting/prob6.class | Bin 0 -> 1455 bytes Searching&sorting/prob6.java | 68 ++++++ Searching&sorting/prob7.class | Bin 0 -> 1728 bytes Searching&sorting/prob7.java | 54 +++++ Searching&sorting/prob8.class | Bin 0 -> 994 bytes Searching&sorting/prob8.java | 49 ++++ Searching&sorting/prob9$Pair.class | Bin 0 -> 344 bytes Searching&sorting/prob9.class | Bin 0 -> 2184 bytes Searching&sorting/prob9.java | 81 +++++++ Searching&sorting/temp.class | Bin 0 -> 539 bytes Graph/pro => Searching&sorting/temp.java | 0 Stack/Probs/SQ10.java | 98 ++++++++ Stack/Probs/SQ11.class | Bin 0 -> 925 bytes Stack/Probs/SQ11.java | 69 ++++++ Stack/Probs/SQ12.class | Bin 0 -> 1854 bytes Stack/Probs/SQ12.java | 98 ++++++++ Stack/Probs/SQ13.class | Bin 0 -> 1107 bytes Stack/Probs/SQ13.java | 60 +++++ Stack/Probs/SQ14.class | Bin 0 -> 1993 bytes Stack/Probs/SQ14.java | 73 ++++++ Stack/Probs/SQ15.java | 5 + Stack/Probs/SQ16.java | 113 +++++++++ Stack/Probs/SQ17.java | 53 +++++ Stack/Probs/SQ18.class | Bin 0 -> 2024 bytes Stack/Probs/SQ18.java | 119 ++++++++++ Stack/Probs/SQ19$petrolPump.class | Bin 0 -> 356 bytes Stack/Probs/SQ19.class | Bin 0 -> 1617 bytes Stack/Probs/SQ19.java | 82 +++++++ String/1_index.txt | 19 +- String/prob_str12.java | 1 + String/prob_str13.java | 2 +- String/prob_str14.java | 1 - String/prob_str17.java | 1 + String/prob_str18.class | Bin 902 -> 901 bytes String/prob_str18.java | 18 +- String/prob_str20.class | Bin 846 -> 846 bytes String/prob_str22.java | 2 + String/prob_str24.java | 1 - String/prob_str25.java | 48 ++++ String/prob_str26.java | 141 ++++++++++++ String/prob_str7.class | Bin 1349 -> 1348 bytes String/prob_str7.java | 2 +- String/prob_str8.java | 1 - String/prob_str9.java | 3 - Tree/TreeProblems/aindex.js | 1 + Tree/TreeProblems/index.txt | 20 +- Tree/TreeProblems/tree_prob1.java | 1 + Tree/TreeProblems/tree_prob10$Node.class | Bin 475 -> 475 bytes Tree/TreeProblems/tree_prob10.class | Bin 1385 -> 1386 bytes Tree/TreeProblems/tree_prob10.java | 17 +- Tree/TreeProblems/tree_prob13.java | 3 +- Tree/TreeProblems/tree_prob15.java | 5 +- Tree/TreeProblems/tree_prob17.java | 1 + Tree/TreeProblems/tree_prob18.java | 2 + Tree/TreeProblems/tree_prob19.java | 2 +- Tree/TreeProblems/tree_prob3.java | 2 +- Tree/TreeProblems/tree_prob7.java | 5 +- Tree/TreeProblems/tree_prob8.java | 3 +- Tree/TreeProblems/tree_prob9.java | 3 + getTranquilApys.js | 132 +++++++++++ tranquilLpPools.json | 65 ++++++ 170 files changed, 5228 insertions(+), 62 deletions(-) create mode 100644 Array/ArrayProbs.java/ExtendedNum.class create mode 100644 Array/ArrayProbs.java/aread.txt create mode 100644 Graph/aindex.txt create mode 100644 Graph/prob27$Coordinate.class create mode 100644 Graph/prob27.class create mode 100644 Graph/prob27.java create mode 100644 Graph/prob28_graph$Ele.class create mode 100644 Graph/prob28_graph.class create mode 100644 Graph/prob28_graph.java create mode 100644 Greedy/prob10_grdy$1.class create mode 100644 Greedy/prob10_grdy$ItemValue.class create mode 100644 Greedy/prob10_grdy.class create mode 100644 Greedy/prob10_grdy.java create mode 100644 Greedy/prob11.class create mode 100644 Greedy/prob11.java create mode 100644 Greedy/prob12_grdy.class create mode 100644 Greedy/prob12_grdy.java create mode 100644 Greedy/prob13_grdy.java create mode 100644 Greedy/prob14_grdy.class create mode 100644 Greedy/prob14_grdy.java create mode 100644 Greedy/prob15_grdy.class create mode 100644 Greedy/prob15_grdy.java create mode 100644 Greedy/prob1_grdy$1.class create mode 100644 Greedy/prob1_grdy$Activity.class create mode 100644 Greedy/prob1_grdy.class create mode 100644 Greedy/prob1_grdy.java create mode 100644 Greedy/prob2_grdy.class create mode 100644 Greedy/prob2_grdy.java create mode 100644 Greedy/prob3_grdy.class create mode 100644 Greedy/prob3_grdy.java create mode 100644 Greedy/prob4_grdy.class create mode 100644 Greedy/prob4_grdy.java create mode 100644 Greedy/prob5_grdy.java create mode 100644 Greedy/prob6.java create mode 100644 Greedy/prob7_grdy.class create mode 100644 Greedy/prob7_grdy.java create mode 100644 Greedy/prob8_grdy.class create mode 100644 Greedy/prob8_grdy.java create mode 100644 Greedy/prob9_grdy.java create mode 100644 Heap&Hashing/aindex.txt create mode 100644 Heap&Hashing/prob10.class create mode 100644 Heap&Hashing/prob10.java create mode 100644 Heap&Hashing/prob11.class create mode 100644 Heap&Hashing/prob11.java create mode 100644 Heap&Hashing/prob12.class create mode 100644 Heap&Hashing/prob12.java create mode 100644 Heap&Hashing/prob13.class create mode 100644 Heap&Hashing/prob13.java create mode 100644 Heap&Hashing/prob14.class create mode 100644 Heap&Hashing/prob14.java create mode 100644 Heap&Hashing/prob15.java create mode 100644 Heap&Hashing/prob16.class create mode 100644 Heap&Hashing/prob16.java create mode 100644 Heap&Hashing/prob17.class create mode 100644 Heap&Hashing/prob17.java create mode 100644 Heap&Hashing/prob9.class create mode 100644 Heap&Hashing/prob9.java create mode 100644 Linkedlist/SigleLinkedlist/CloneList$Node.class create mode 100644 Linkedlist/SigleLinkedlist/CloneList.class create mode 100644 Linkedlist/SigleLinkedlist/CloneList.java create mode 100644 Linkedlist/SigleLinkedlist/FlatternList$Node.class create mode 100644 Linkedlist/SigleLinkedlist/FlatternList.class create mode 100644 Linkedlist/SigleLinkedlist/FlatternList.java rename {Searching => Searching&sorting}/BinarySearch.java (100%) rename {Searching => Searching&sorting}/LinearSearch.java (100%) create mode 100644 Searching&sorting/Node.class create mode 100644 Searching&sorting/NodeComparator.class create mode 100644 Searching&sorting/aindex.txt create mode 100644 Searching&sorting/prob1.class create mode 100644 Searching&sorting/prob1.java create mode 100644 Searching&sorting/prob10.java create mode 100644 Searching&sorting/prob11.java create mode 100644 Searching&sorting/prob12.class create mode 100644 Searching&sorting/prob12.java create mode 100644 Searching&sorting/prob13.java create mode 100644 Searching&sorting/prob14.class create mode 100644 Searching&sorting/prob14.java create mode 100644 Searching&sorting/prob15.java create mode 100644 Searching&sorting/prob16.class create mode 100644 Searching&sorting/prob16.java create mode 100644 Searching&sorting/prob17.class create mode 100644 Searching&sorting/prob17.java create mode 100644 Searching&sorting/prob18.java create mode 100644 Searching&sorting/prob2$pair.class create mode 100644 Searching&sorting/prob2.class create mode 100644 Searching&sorting/prob2.java create mode 100644 Searching&sorting/prob3.class create mode 100644 Searching&sorting/prob3.java create mode 100644 Searching&sorting/prob4.class create mode 100644 Searching&sorting/prob4.java create mode 100644 Searching&sorting/prob5.java create mode 100644 Searching&sorting/prob6.class create mode 100644 Searching&sorting/prob6.java create mode 100644 Searching&sorting/prob7.class create mode 100644 Searching&sorting/prob7.java create mode 100644 Searching&sorting/prob8.class create mode 100644 Searching&sorting/prob8.java create mode 100644 Searching&sorting/prob9$Pair.class create mode 100644 Searching&sorting/prob9.class create mode 100644 Searching&sorting/prob9.java create mode 100644 Searching&sorting/temp.class rename Graph/pro => Searching&sorting/temp.java (100%) create mode 100644 Stack/Probs/SQ10.java create mode 100644 Stack/Probs/SQ11.class create mode 100644 Stack/Probs/SQ11.java create mode 100644 Stack/Probs/SQ12.class create mode 100644 Stack/Probs/SQ12.java create mode 100644 Stack/Probs/SQ13.class create mode 100644 Stack/Probs/SQ13.java create mode 100644 Stack/Probs/SQ14.class create mode 100644 Stack/Probs/SQ14.java create mode 100644 Stack/Probs/SQ15.java create mode 100644 Stack/Probs/SQ16.java create mode 100644 Stack/Probs/SQ17.java create mode 100644 Stack/Probs/SQ18.class create mode 100644 Stack/Probs/SQ18.java create mode 100644 Stack/Probs/SQ19$petrolPump.class create mode 100644 Stack/Probs/SQ19.class create mode 100644 Stack/Probs/SQ19.java create mode 100644 String/prob_str25.java create mode 100644 String/prob_str26.java create mode 100644 Tree/TreeProblems/aindex.js create mode 100644 getTranquilApys.js create mode 100644 tranquilLpPools.json diff --git a/.DS_Store b/.DS_Store index c522e56e0b1b1f14afe99053a61adc65f30c9c99..7075698243ab74b404dbde8ec80251eb1b5b6de9 100644 GIT binary patch delta 833 zcmbu7&q~8U5XQglKLram#cD_tb5TU4PvAvGtd}<6#e@+a_LP(A+I4w z$x(d;Px>%=(a9jCS;RxTm)&K)`OSVa+c*2>Lrqi%=JTwmM)|^<&<|YCuDf0xKmka7 z&|d!Lh458*33Tk>1n01DfgTRg;FFCOR_W$a%;9(w2D*H5;Gz2m_VE`>6_93XC#g#B zQbbZkH^qAqWU)`>E%<0jDFZ1b$I1ph(?Kt(%`8jWJSuF*Co2`Ax5-p&wJGJ@1yW*> zWj-#^!5*$D^^Bh8608iH_88SpLa+^p^^p!J|1eI8a0P2fnBm#rDMo~D$q0{1@6zDJ z(g;7&=QqWIl9(17BcttbQPpzdmRVb>7Oklpsg-GR(qI>{10VjdHkTHkEcdm!=vb>| ZqbcJn6VP`VzonCRv@%gk$LXk0egKtq+{6F? delta 805 zcmZn(XbG6$<EdU^hQw;AS3ybBvRPgywJ76`sUc&%uz+P{fePP{5GEkjaqDP@I!) z7@VA+TfhJYtP6k?hML@b7nh`*{3Ng(1H%KoLx&x)t4krEt{!4(K?bs=3P7_MSQtDQ zQb7*$%*juNS|-52z|;(sbNUYkAY}-3s17%ti!6ug;D$xY5C^j`m_aSc%|~`Ak^-na zsskG)pBH_*`GuG?BQGaIFxZ(zz_81htRNv;FAcQV0m*?VDuCY2V@OAJDtie~2NqRm zj=svP2@YkfDiN;NWngH)qZHL63Y#4z?3gyMmx^GWSP-+BUEvpt9V}>uUC7Ab3mE`a C5Wi0V diff --git a/Array/ArrayProbs.java/ExtendedNum.class b/Array/ArrayProbs.java/ExtendedNum.class new file mode 100644 index 0000000000000000000000000000000000000000..ff5fe60aaf1e5af436da20cf227ca5ef4176f0ce GIT binary patch literal 1325 zcmaJ>+foxj5Iqx;ELoNWkXr;16fi_C0xAl4BY*@0K7@j@C`%{F7#5b@xI3ZbPki@* zSFMsuVU-`?zxWGcPZA0+DXTKQGiT3spYEQ{uRo_h0Zd^TOa!Kj8Y4fhxt9oNj8Hn-NfRTK;?N!YHFGe4LjcaAMH z1ZPd#lusD~v1D>+oxz`Qa>S3MOk1oLcQe9W;~9&P#@EY-n9(q6;0c}@Xu&mxra8xvo^*L(MaV5D=S6~e zR*&ZfUSN))Vd0Y$c249dIU-*Kd!5-9S$PFIPp&SeD${(yP1;iAh0D+uOV-T0EmmC( zC)eU*Y3}sqsK)dQ+bx?-z zh3u50S`{jA*AwM^O`Xd+5|}4-n{2q3y``4y@*R@1fXrre^PC%G*>hW6NUt*9Cn zRJkd`{)_0Qz31$R%H1e?TjW{kxceGjQM8of>=X+OM$)#0o3Oa&2@3J~a%n0)%AH-} zcFq!BfBD0i>f|pWS3X?ZFNhlS%}f09ZMahXii-rdth6Zw-MbXSKvjOVv@!JjpGTt} zrojh%v}hd2LS1LFKG1Zbjchxe4ruU$^jwJ_gT=cJ;p;j<-Rckc-;5k1Fzr{nV+5xI z(ZCV3ZvXo)2uA}^{}Jjp4$ginG*n0M5%ksg$O#$_VSFov=^z`2PBu(IA_$R?FiGho zA$=rem}E?mhzzxPo2<3EaN5p&E2JQJ)MVXjr;|Tu|YZj literal 0 HcmV?d00001 diff --git a/Array/ArrayProbs.java/Query.class b/Array/ArrayProbs.java/Query.class index 60a6940502d326ea6433d24bd6a5dd2d9940eda4..a2cc705b0dae517606ce3b12960dae6c820b4a20 100644 GIT binary patch delta 30 jcmeBW>SdbnO`MB?g@K!alYxhUkAatg5r`QWm>Bo~PGbWj delta 30 jcmeBW>SdbnO`M&9g@J>C6A1YjxEL52co`TNm>Bo~O_u`~ diff --git a/Array/ArrayProbs.java/aread.txt b/Array/ArrayProbs.java/aread.txt new file mode 100644 index 0000000..e5c6134 --- /dev/null +++ b/Array/ArrayProbs.java/aread.txt @@ -0,0 +1,27 @@ +1.min max in array +2. reverse the array +3.Largest Sum Contiguous Subarray (kadanes) +4. find duplicates and find duplicates withim k distance +5.Chocolate Distribution Problem (distribute n Chocolate amongs m student) +6.search in sorted and rotated array +7.next permutation +8.find repeting and missing element +9.find min element in sorted and rotated array +10.stock busy sell to maximum profit +11.kh smallest and largest +12.trapping rainwater +13.max product subarray +14.check whether sum pair exist in sorted rotated array +15. Container With Most Water +16.product of array expect itself +17. +18.merge intervales +19.no of merge operations to make array palindrome +20. +21.Arrange given numbers to form the biggest number +22. +23.Print all possible combinations of r elements in a given array of size n +24.find sum query in specific range(h) +25.longest subarray with sum divisible by k +26.next greater +27.next smaller \ No newline at end of file diff --git a/Array/ArrayProbs.java/array_prob16.java b/Array/ArrayProbs.java/array_prob16.java index e8c43f9..64d424a 100644 --- a/Array/ArrayProbs.java/array_prob16.java +++ b/Array/ArrayProbs.java/array_prob16.java @@ -26,6 +26,53 @@ void productArray(int arr[], int n) { return; } + void productArray2(int arr[], int n) { + + // Base case + if (n == 1) { + System.out.print(0); + return; + } + // Initialize memory to all arrays + int left[] = new int[n]; + int right[] = new int[n]; + int prod[] = new int[n]; + + int i, j; + + /* + * Left most element of left array + * is always 1 + */ + left[0] = 1; + + /* + * Right most element of right + * array is always 1 + */ + right[n - 1] = 1; + + /* Construct the left array */ + for (i = 1; i < n; i++) + left[i] = arr[i - 1] * left[i - 1]; + + /* Construct the right array */ + for (j = n - 2; j >= 0; j--) + right[j] = arr[j + 1] * right[j + 1]; + + /* + * Construct the product array using + * left[] and right[] + */ + for (i = 0; i < n; i++) + prod[i] = left[i] * right[i]; + + /* print the constructed prod array */ + for (i = 0; i < n; i++) + System.out.print(prod[i] + " "); + + return; + } public static void main(String[] args) { array_prob16 pa = new array_prob16(); int arr[] = { 10, 3, 5, 6, 2 }; diff --git a/Array/ArrayProbs.java/array_prob21$1.class b/Array/ArrayProbs.java/array_prob21$1.class index d6af7943de8ce40aa006af9d2086a97573b1bb19..98170e3f3fc440e3ae4dea2b04c57cafa1db6a74 100644 GIT binary patch delta 33 ncmX@dd5&|#duB%E$sd?qIkgx#7<3r~84M@evA6=oT3EaQslNz~ delta 33 ncmX@dd5&|#duB$q$sd?qIe8g47z7vu8AK-AvA6=oT3EaQp+E=x diff --git a/Array/ArrayProbs.java/array_prob21.class b/Array/ArrayProbs.java/array_prob21.class index b8117e37f249ec98d225b31bbd2532c39e645034..8c5cb0527983ab50ad2eb51e77e45358970b354e 100644 GIT binary patch literal 2760 zcma)8>vI!T6#v~O?WW1n7qkVjRA`YTZ7I(Rq!wtTl9CoQ(9#0Jwpr4po87S4U<z4wR^5Lk26rV|VGp96T zkAw;CPSgjD&!avZ^I_5l-H&#pxeh~uDIvok#|%TYqPmjJs#%7LZq3l_9tKY^G{oSI znn{(RI<6V&U@kqTT6>i-ohWj~(hNJUSSdAYGt>v;$CMLFXU^92&LMT&HmwMkUy!hs z@yP)tBg7;eXQ)hQDMPVy7HJ9HDc0>M(iJ1snXt)7D$?Vq(j8-t8w{;(*|?UqBcVG* z88+X}<~9&BY&E4?+``>ty=g@=7#e~H?%d_kHRwuuEUC1Xc-Fdxp(z;OF=eYpQcaS( zk&=&4jKQBUbJn=pr*SB270Xhl4`(cMY~9+`97cw~Ai+AIa=^1PIzc+C+-$9DC0H`D zuw~?MLdKJrk}xgfBu>eA3QtRTM#i&vPR40GPc}q$1gM3WWxRkh63)ta5$6~d7Sp$# zyTbvMa9+ksd^g~VM#jr{MaHW*#~pi3#_M>4p{Ca~?W}DnnE}_U1G_sZu2G;ynrPbEiJwYA?$85Fart5&~((p6Kk=QU%w^TG3ml z*ci$-ZlI#wxS>mon~2c0M#g$^g%0(|1o7gSG z%iNPzrWnHRMk-=a(m4*4WXNZmPJ$_gC9XJB;&4(ZOwDsv=&F&jCq(SjBvnP|IkFsc z?IiV!C#7-#f-!f`7A+GRLyDdw#`0h+Cj3{D$^VFM)Q?Z`8N;eVaPH7uJzvlsit+RF zb4t^=NG;h|JRjZd8K<+)w6v6FD0;yib}J@fC2kri?p41#j9c)`AE+*XL=jaenGBsP z4C~zijmaSY^%c=ae-Ti z*+nT4+&i67-R%E=(=mB(SvU9v%~3_y6V$5_3EwiTyaSNC#lx`d-h5b2mD53YI#3SA zPjnjB(pMABj8nriU_a7=VI7SXg4hfnKf>sZ!C8;MLn|N@o&hVv+ow_QaA z!$s8n1c}x@hCC`S-~5BCD--G($SUY15Wq&%(92{Ay1hgIMGd1GYH6QC?MS%kD(cE0I2SIR z!J<6shtGJ}<(t2^Uqb^xUeBSCgclEby1ez?_B@tc!paU#Y_Ip`ao=^+Ucu6{v$%f- zO?fOEKI0|v-{#Of(vimlGg!XGyM!25{2=`0c&&p><5qeiZ6h1ou>!s5rnwh=*oB=) z(3|Wq`f-Zp(-@#jYqto#5#AeE%p_E?zYzKd3nettDqMgfLQr($VM+#1zz9Ji5-^7r z^1n6SR<|;b2Z!70RykA9nL=WkMYx#HWspe0KFa5QRFk3xj8f_kpcMxx5r=C0y!{Gh zTHqCC0&Q2&7N);?{(BO37e*hkY$IBk2odx}7amp(P delta 515 zcmYk2-%b-j6vltEMQ1x5p%&Ysptia|YpF}2El^Yx{{bP9D@?sHTQLUG2x)-Cc)>G} zeG)>VMiZ|Mckm*-05P6jZpH)q;%;MYgmW+jWD_pZqtSEis%g zzoRJA56UtiffSLGJ0GsOx$KZ|S0#f!+{j&aln=kUt%FF(aV6GM43QQ!(o3?eVPTUv z7o;^Kd2UPUa7U=S6e4TM+rl`4WrV~k0Uamh+@%JPY#lsVkvzF?m`bGRXqi6aT%9}V?J1^@s6 diff --git a/Array/ArrayProbs.java/array_prob21.java b/Array/ArrayProbs.java/array_prob21.java index c346369..4fe1e7b 100644 --- a/Array/ArrayProbs.java/array_prob21.java +++ b/Array/ArrayProbs.java/array_prob21.java @@ -56,6 +56,13 @@ public int compare(String X, String Y) { } } + public static String findLargestNumber(List nums) { + // sort using a custom function object + Collections.sort(nums, (a, b) -> (String.valueOf(b) + a).compareTo(String.valueOf(a) + b)); + return nums.stream() + .map(Object::toString) + .collect(Collectors.joining("")); + } // using int public static String largestNumber(List arr) { // finding number of digits in maximum element diff --git a/Array/ArrayProbs.java/array_prob24$1.class b/Array/ArrayProbs.java/array_prob24$1.class index 0f508bf88954e0e6de11ddbe1c1e43a326b5096a..731f55a373f8e6a7986fffaa6ef08292d525f22d 100644 GIT binary patch delta 33 ncmbQsHkWOKBNL!zLGOf?PBiwYfyEBBLuBU5+ou!b>BO2 zc)Eu%FPCkuFz)6|D6$s9tKr&}<$33`O3TdUs!fPVn`>ORImBV-r~2-+X+?&`6gQl2 zDMQYbHsqOhF=n0DTBVwE_Our&;w1FptZeC^yEK$A&J&yOeARP`56YQGBFMn&!jeKh zsBv^s<#g8x80BiiX*XuPZ?OWNO;Vi=qby;=CTS17>gE328%a#Tg_2#$R52qXoTr8;wX9Od1DV}pnf4Q!c}feUQh`9Ong2r=6ejr;;gi%7SE|I%Fho4u-N7H)B7L}e2Q#FZ zTV!lX_HLg_DU+`*RodTfr6ifjq4eY?Vc~m9e6M7jmfiFRmjrwu delta 745 zcmYk4OHWf#5XXO~x3{Og+yYWtM4^>Oc|TM@L{Xli6i^Wb@kte;MUrYM7*@nY<5qIr zv2vq36I=j_F>&iBaI0THm%31#TTS%b+&MF6X8tq(IpbZL%jPOPRL zsP5IzkMklFYkF*Y>2vO@&`N}U&4A5G25nApT49bY&SsWvhDg{9lhBOVjB-X%*q2Uc z7qXe;z0uk1o%GB?fseC(&e@D{UNdfUfs2aJTyiPdvY1WHxAbN*$>ovMLe?h2gv}(E zY^JzuvzL7eJL&j6UrmcETy;u~VdsY@>Q#hmopKd%R*Y8PH5Yr@*)r R + 1) { currSum -= a[currR - 1]; currR--; diff --git a/Array/ArrayProbs.java/array_prob4.java b/Array/ArrayProbs.java/array_prob4.java index 2833645..74f2e4f 100644 --- a/Array/ArrayProbs.java/array_prob4.java +++ b/Array/ArrayProbs.java/array_prob4.java @@ -3,6 +3,7 @@ import java.util.*; public class array_prob4 { + static boolean duplicate(int arr[], int n) { HashSet hs = new HashSet<>(); for (int i = 0; i < n; i++) { @@ -15,6 +16,26 @@ static boolean duplicate(int arr[], int n) { return false; } + /* + * Java program to Check if a given array contains duplicate + * elements within k distance from each other + * Input: k = 3, arr[] = {1, 2, 3, 4, 1, 2, 3, 4} + * Output: false + * All duplicates are more than k distance away. + * + * Input: k = 3, arr[] = {1, 2, 3, 1, 4, 5} + * Output: true + * 1 is repeated at distance 3. + * + * Input: k = 3, arr[] = {1, 2, 3, 4, 5} + * Output: false + * + * Input: k = 3, arr[] = {1, 2, 3, 4, 4} + * Output: true + * + * + * + */ static boolean checkDuplicatesWithinK(int arr[], int k) { // Creates an empty hashset HashSet set = new HashSet<>(); diff --git a/Array/ArrayProbs.java/array_prob9.java b/Array/ArrayProbs.java/array_prob9.java index 1c8668e..1220e53 100644 --- a/Array/ArrayProbs.java/array_prob9.java +++ b/Array/ArrayProbs.java/array_prob9.java @@ -1,4 +1,4 @@ - +//find minimum element in sorted and rotated array public class array_prob9 { public static int findMin(int arr[]) { if (arr.length == 0) { diff --git a/Array/FactorialOfBigNumber.java b/Array/FactorialOfBigNumber.java index 9f56892..8a293c0 100644 --- a/Array/FactorialOfBigNumber.java +++ b/Array/FactorialOfBigNumber.java @@ -43,7 +43,6 @@ static BigInteger factorial3(int n) { // and returns the new value of res_size static int multiply(int x, int res[], int res_size) { int carry = 0; // Initialize carry - // One by one multiply n with individual // digits of res[] for (int i = 0; i < res_size; i++) { diff --git a/GPP/prob77.java b/GPP/prob77.java index 371d4eb..876e559 100644 --- a/GPP/prob77.java +++ b/GPP/prob77.java @@ -5,54 +5,56 @@ // student is a minimum public class prob77 { - static boolean isPossible(int arr[],int n,int m,int min){ - int studentRequiered = 1,sum = 0; - for(int i = 0;i min) { return false; } - //pages we are giving to current student - if(sum+arr[i] > min){ + // pages we are giving to current student + if (sum + arr[i] > min) { studentRequiered++; - //if we want to give min pages to student cant increase it ferther + // if we want to give min pages to student cant increase it ferther sum = arr[i]; - if(studentRequiered > m){ + if (studentRequiered > m) { return false; } } else { - - sum+=arr[i]; + + sum += arr[i]; } } return true; } - static int allocateMinimumPages(int arr[],int n,int m){ - int sum = 0; - if (n < m){ - return -1; - } - for(int i = 0;iO$O=hIAKN@i=v?;HxhL7U^vAY z{o~M+Eef(BgmEII$H?6$>=L`C35#+Ve}cs)E41R%6|9f-U_jU>Az(z9(AovIaY+kX T)N4^4u5*Na%0|*gggtnF+2A{k literal 0 HcmV?d00001 diff --git a/Graph/prob27.class b/Graph/prob27.class new file mode 100644 index 0000000000000000000000000000000000000000..effcd67081d914d724a0e04ebdd6a74a4b671314 GIT binary patch literal 2212 zcmah~TWl0n82(P@)}5Vpx4CoMsb$1q0 zjKV`-h!1K^41os;FFYD=AfTv;#)Jn$e8X4ci$3{eLZJ0OGYcIq(WL$7od5jacmCV? z_txz7n*i41h>k_*(y&6q3pymRT&Y7rER0Tc3lSG$l@O~#bg)K zA=YcypkpC6YS^TqpFtmToJ!so~foaOPW^QW4EPJLJ28gC;+9ih8 z*!b{q^Mu)3FiXdJGj7E$9qShmJ>%3WIctY4sKe!oGm%)|BP?k*YE|74OI%$wuoz3o zHM)plk;hbX?LsekH)Z9A$rXkcAKf({qd*NB*o-X(UdAg1wqnS@Hf%Sr13L}u!cGk- z1G}+@A-dIZ+^SnK%OjRM>Ex>s6~m1fF))g>hP?*%VZVWl@S|azQ0-VsvHO=2d_KJN z#BnP}4n^ku+*h+|6rd7Id5MzDe4c^F0y*(P{oRKdG`qUJSazqqQqW$m+NTIib)n$p zvQsEf4r1L;g2|@hoMd2RC*>S63wV{8uDVu{4xAeK#(lKy^zNlvxKt6#EcWX-fP)ks zTgI@sXiix}PAO-)W41dCpGv!Q!kMz_4dXkr!_2u(Wm>~HWq;UlrfOw|bHP;BL4Fx`nWcQes&@I7{eh&_ zeF$hC0UnqxTTd|$_VI(7JxMWS777{LwfZ%@#<1dvfS%?XL+5|n;W>KCi|B=erUDfR zOGviSu7kdezDoQm*k`n0c!s3vDZ8PIR;4wWN~1I?T7U*Qesdr$C2kJ3FZ~G(4Wl<8 zWv@csBuhz!EA5w%l#(h}mtMlkI9C!}?U65{wN1VOCCe4AUWIxMS_8&rRCamp&Wu9x z7Gc}uYiMLR&up;@F(g$fsd0^~m)KsR(iy&ovZ--RTjQ4qCxkS(lJ<6TJ{j^9Nu7r- zU?UHaBkQ<+0X81y$IiG6a?3Q-u@U z2vCK&5ug%>b*f~OM2A5cYns(doaBZ4a8 zQAGt+)TfFhcr-v2;n4tf8oNCEsYv4NC;9AdhGy_)< z5%zO`kp2pyUb$}jYtbnUUZ?zmb+qoIwo0NA8xTQ1HP-+&+#upKKl`wShUFkV&jFec z+c1XhFtHQIk%EgoID-+qPxJ8{_Tv*8kzbM3cQ}Y&aR|TRFn-54{uD0(N0^S+SqI)= zE0ANWk!O9d*dDye4&oS_#3U=Dz)qsb&Y;9ThQltR%)Y=|>;_Wo2b^F(;w1YS)9f}* zu{(I1{YBru@ecckboX((K_YKDD4IN4=BV*ijm8-xp`nxRzenA<{4NywyGIB2!5N!H zL4(3*v%4Y|<%b&5dK$&k(79aK46phc3m$_%F#bQdoX(7_CiwgSXr;#v%uq4UQUTw?DSUu; s@gZa?tSJ5SSWaJ=+*i;_s|BP}XvT1Af-x%Ft28oRBz+@UB queue = new LinkedList<>(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (matrix[i][j] == 1) { + queue.add(new Coordinate(i, j)); + } + } + } + // initialize minDistance as 0 + int minDistance = 0; + while (!queue.isEmpty()) { + // initialize size as size of queue + int size = queue.size(); + // Run a loop size times + for (int i = 0; i < size; i++) { + // remove an element from queue + Coordinate curr = queue.poll(); + // ans to this coordinate is minDistance + ans[curr.row][curr.col] = minDistance; + // enqueue all the valid adjacent cells of curr that are equals to + // 0 in the matrix array and set them as 1 + // left adjacent + int leftRow = curr.row - 1; + int leftCol = curr.col; + if ((leftRow >= 0 && leftRow < n) && (leftCol >= 0 && leftCol < m)) { + if (matrix[leftRow][leftCol] == 0) { + queue.add(new Coordinate(leftRow, leftCol)); + matrix[leftRow][leftCol] = 1; + } + } + // right adjacent + int rightRow = curr.row + 1; + int rightCol = curr.col; + if ((rightRow >= 0 && rightRow < n) && (rightCol >= 0 && rightCol < m)) { + if (matrix[rightRow][rightCol] == 0) { + queue.add(new Coordinate(rightRow, rightCol)); + matrix[rightRow][rightCol] = 1; + } + } + // up adjacent + int upRow = curr.row; + int upCol = curr.col + 1; + if ((upRow >= 0 && upRow < n) && (upCol >= 0 && upCol < m)) { + if (matrix[upRow][upCol] == 0) { + queue.add(new Coordinate(upRow, upCol)); + matrix[upRow][upCol] = 1; + } + } + // down adjacent + int downRow = curr.row; + int downCol = curr.col - 1; + if ((downRow >= 0 && downRow < n) && (downCol >= 0 && downCol < m)) { + if (matrix[downRow][downCol] == 0) { + queue.add(new Coordinate(downRow, downCol)); + matrix[downRow][downCol] = 1; + } + } + } + // increment minimum distance + minDistance++; + } + // print the elements of the ans array + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + System.out.print(ans[i][j] + " "); + } + System.out.println(); + } + System.out.println(); + } + + public static void main(String[] args) { + // Example 1 + int matrix1[][] = new int[][] { + { 0, 1, 0 }, + { 0, 0, 0 }, + { 1, 0, 0 } + }; + minimumDistance(matrix1); + // Example 2 + int matrix2[][] = new int[][] { + { 0, 0, 0 }, + { 0, 0, 0 }, + { 1, 0, 1 } + }; + minimumDistance(matrix2); + } + +} diff --git a/Graph/prob28_graph$Ele.class b/Graph/prob28_graph$Ele.class new file mode 100644 index 0000000000000000000000000000000000000000..20580b299a14541ccca52404b015af7499e510fb GIT binary patch literal 372 zcmYjMJx{_=6g{t{w8bh#`~Y-taDWbyxaeS92uc-k(6E{oU!bJ6q%B5&mV+^I@CW## zjOQ^ioOABG@1ApWfB(LJ0Gy#!fq|Nh61El9P3)N17Z7iRPrM71FQOzWE(MIX?{~%m zrC$0h1**d+k)!2HD6_{PjM=F?q|0m~uOjuREwVH`J%5^J!D4nY4_*TSYb5hxkmiMn zh65W-2W6NJESLiBy5YF5GV~QYev-(n7YBJRbIz%(ZX6`j?tM6ylS05*x6;<`jB&(! z3?8WwTtbH0Ll%UM3Uz~3pA$N@>3uQaSHcSkyOJG1Q05-=p1 z*r z-oE|?fVD`6QH2K#JXi_?tL3uBz}hf$Nn97^dHoEm!UnlC%VlF23O31QvpjB*yR8Pc z$@lhBv|vXFJHyz8hh`Jt5d&=k>dv$!5NUNBE8CJbb2%#~AolZV6`0xLIyujDyn|*s zZ>dyL$!L)qU7%#6?bzOC+K8_>D4?~tDVi#4vmI+sexTRN9x!{Qal_70-%bhW@z&NA zhiJFcGn4)8W@buahn2Pm1fub_OxEpfT6g4V*39%Rp?A$vBb4m3lKtD#X~M?4yL~I+ ztm}1TP3Nd|xj=0-&~9K4of$A~N1!U+-FD18VK$~I*4XJ~ZRcpSbT-`S=Ces_mn|JE z4?;Fbd4U;wten?w$uM#eEJTb+3W`P0f$9kMqFSKRhsb+&x{<;6Td6iX=Ly^sl$Vi6 zJNqKokIo1V;L!*UqAP-BSRTQ>SQ5cw@)*Yo0j0Y&f;!Y2NJMZ5-He2>$J|1+v83rZ zt`}qc1|E;#2^=QccGvZC9<$bNd3|mwS5|@}A@oFGqL=KcG<5VHvy${rWgc0tDd+d) ztvu5qPVzZbtQK>nnkm+fmHD>`zcQ@u&Vh_ad0qonO3PSQKXVda@n3nCDQgY5CkPVo zr}I?Kvsio8&C{!BLCtm>_p(|ZYi5}P%>orZ`kiFnt&9{(v($I^H(BX0lA!bP1NMLw z%UZ|tcGgP8o^-P@GmuZumAQ;uRD; zV98W|Z0CgAZxt_G!PqV{>ABfc297ZcZLZs&&j_3eCbg(kDBo_=Nu{mal7eJ&AeTkl z0ObzF1E(_9G~&TNC|rQ%U@%1!EzC-%?ODwRSi`0N31~Xs1Qy&~4vRQ{syH(g%;T>b z0yX}rmZ$lF^8%ER$6n*Qh!XSp7IN0qjX+%HMqn{lDFkdoNOlePQnZ=I6~5ZV%yQdw8iRNJ5pLD$|NRK)Q3pM!$yt$=$AIM#u~ zT#sNDdN7A~YaaItNn46uAFmwx7!)yv5>fUSbp9Cvr$qrY`dxRBzCS5UsxfBN5f2`UpbTP^zG7P^VYF4QgD!^SO#L$*aGH zu)sNSlQy}ZA@CK9QAEy(*C&tdE15j4hpRS#K~-pLv>;FK zSefuuuR`^KrJhupgfH+@oH59Yxwq|;*Kv_J5>1c zfuauIuCE(K*;yD0yJh}Vw|t8xUdLm+UulHlpaL#xkzuFO_P1rPSeTWfi{hTW3Ei$1xMSft3b7kvQ)$hLBiXXrr<*-sf@bnBW^Q zq{P~K`CB!P(g}vI_!kx`VfK9~8qiqm`^#)x+4uR9&v8#e4Sg0)sCq|2(>fBm+L0*X z-q1Qa6PnK-U@j@MY0Ka)j{{zZsS55!` literal 0 HcmV?d00001 diff --git a/Graph/prob28_graph.java b/Graph/prob28_graph.java new file mode 100644 index 0000000..33d7db6 --- /dev/null +++ b/Graph/prob28_graph.java @@ -0,0 +1,214 @@ +import java.util.LinkedList; +import java.util.*; + +//rotane oranges +/** + * + * Minimum time required to rot all oranges + * Given a matrix of dimension m*n where each cell in the matrix can have values + * 0, 1 or 2 which has the following meaning: + * 0: Empty cell + * 1: Cells have fresh oranges + * 2: Cells have rotten oranges + * Determine what is the minimum time required so that all the oranges become + * rotten. A rotten orange at index [i,j] can rot other fresh orange at indexes + * [i-1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right). If it is + * impossible to rot every orange then simply return -1. + * + * Input: arr[][C] = { {2, 1, 0, 2, 1}, + * {1, 0, 1, 2, 1}, + * {1, 0, 0, 2, 1}}; + * Output: + * All oranges can become rotten in 2-time frames. + * Explanation: + * At 0th time frame: + * {2, 1, 0, 2, 1} + * {1, 0, 1, 2, 1} + * {1, 0, 0, 2, 1} + * + * At 1st time frame: + * {2, 2, 0, 2, 2} + * {2, 0, 2, 2, 2} + * {1, 0, 0, 2, 2} + * + * At 2nd time frame: + * {2, 2, 0, 2, 2} + * {2, 0, 2, 2, 2} + * {2, 0, 0, 2, 2} + * + * + * Input: arr[][C] = { {2, 1, 0, 2, 1}, + * {0, 0, 1, 2, 1}, + * {1, 0, 0, 2, 1}}; + * Output: + * All oranges cannot be rotten. + * Explanation: + * At 0th time frame: + * {2, 1, 0, 2, 1} + * {0, 0, 1, 2, 1} + * {1, 0, 0, 2, 1} + * + * At 1st time frame: + * {2, 2, 0, 2, 2} + * {0, 0, 2, 2, 2} + * {1, 0, 0, 2, 2} + * + * At 2nd time frame: + * {2, 2, 0, 2, 2} + * {0, 0, 2, 2, 2} + * {1, 0, 0, 2, 2} + * ... + * The 1 at the bottom left corner of the matrix is never rotten. + * + * + */ +public class prob28_graph { + public final static int R = 3; + public final static int C = 5; + + // structure for storing coordinates of the cell + static class Ele { + int x = 0; + int y = 0; + + Ele(int x, int y) { + this.x = x; + this.y = y; + } + } + + // function to check whether a cell is valid / invalid + static boolean isValid(int i, int j) { + return (i >= 0 && j >= 0 && i < R && j < C); + } + + // Function to check whether the cell is delimiter + // which is (-1, -1) + static boolean isDelim(Ele temp) { + return (temp.x == -1 && temp.y == -1); + } + + // Function to check whether there is still a fresh + // orange remaining + static boolean checkAll(int arr[][]) { + for (int i = 0; i < R; i++) + for (int j = 0; j < C; j++) + if (arr[i][j] == 1) + return true; + return false; + } + + // This function finds if it is possible to rot all oranges or not. + // If possible, then it returns minimum time required to rot all, + // otherwise returns -1 + static int rotOranges(int arr[][]) { + // Create a queue of cells + Queue Q = new LinkedList<>(); + Ele temp; + int ans = 0; + // Store all the cells having rotten orange in first time frame + for (int i = 0; i < R; i++) + for (int j = 0; j < C; j++) + if (arr[i][j] == 2) + Q.add(new Ele(i, j)); + + // Separate these rotten oranges from the oranges which will rotten + // due the oranges in first time frame using delimiter which is (-1, -1) + Q.add(new Ele(-1, -1)); + + // Process the grid while there are rotten oranges in the Queue + while (!Q.isEmpty()) { + // This flag is used to determine whether even a single fresh + // orange gets rotten due to rotten oranges in the current time + // frame so we can increase the count of the required time. + boolean flag = false; + + // Process all the rotten oranges in current time frame. + while (!isDelim(Q.peek())) { + temp = Q.peek(); + + // Check right adjacent cell that if it can be rotten + if (isValid(temp.x + 1, temp.y) && arr[temp.x + 1][temp.y] == 1) { + if (!flag) { + // if this is the first orange to get rotten, increase + // count and set the flag. + ans++; + flag = true; + } + // Make the orange rotten + arr[temp.x + 1][temp.y] = 2; + + // push the adjacent orange to Queue + temp.x++; + Q.add(new Ele(temp.x, temp.y)); + + // Move back to current cell + temp.x--; + } + + // Check left adjacent cell that if it can be rotten + if (isValid(temp.x - 1, temp.y) && arr[temp.x - 1][temp.y] == 1) { + if (!flag) { + ans++; + flag = true; + } + arr[temp.x - 1][temp.y] = 2; + temp.x--; + Q.add(new Ele(temp.x, temp.y)); // push this cell to Queue + temp.x++; + } + + // Check top adjacent cell that if it can be rotten + if (isValid(temp.x, temp.y + 1) && arr[temp.x][temp.y + 1] == 1) { + if (!flag) { + ans++; + flag = true; + } + arr[temp.x][temp.y + 1] = 2; + temp.y++; + Q.add(new Ele(temp.x, temp.y)); // Push this cell to Queue + temp.y--; + } + + // Check bottom adjacent cell if it can be rotten + if (isValid(temp.x, temp.y - 1) && arr[temp.x][temp.y - 1] == 1) { + if (!flag) { + ans++; + flag = true; + } + arr[temp.x][temp.y - 1] = 2; + temp.y--; + Q.add(new Ele(temp.x, temp.y)); // push this cell to Queue + } + Q.remove(); + + } + // Pop the delimiter + Q.remove(); + + // If oranges were rotten in current frame than separate the + // rotten oranges using delimiter for the next frame for processing. + if (!Q.isEmpty()) { + Q.add(new Ele(-1, -1)); + } + + // If Queue was empty than no rotten oranges left to process so exit + } + + // Return -1 if all arranges could not rot, otherwise ans + return (checkAll(arr)) ? -1 : ans; + + } + + // Driver program + public static void main(String[] args) { + int arr[][] = { { 2, 1, 0, 2, 1 }, + { 1, 0, 1, 2, 1 }, + { 1, 0, 0, 2, 1 } }; + int ans = rotOranges(arr); + if (ans == -1) + System.out.println("All oranges cannot rot"); + else + System.out.println("Time required for all oranges to rot = " + ans); + } +} diff --git a/Graph/prob4_graph.java b/Graph/prob4_graph.java index 542a996..cf84b48 100644 --- a/Graph/prob4_graph.java +++ b/Graph/prob4_graph.java @@ -2,6 +2,26 @@ import java.util.*; //topological sort +/** + * Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of + * vertices such that for every directed edge u v, vertex u comes before v in + * the ordering. Topological Sorting for a graph is not possible if the graph is + * not a DAG. + * + * For example, a topological sorting of the following graph is “5 4 2 3 1 0”. + * There can be more than one topological sorting for a graph. For example, + * another topological sorting of the following graph is “4 5 2 3 1 0”. The + * first vertex in topological sorting is always a vertex with in-degree as 0 (a + * vertex with no incoming edges). + * + * + * + * + * + * + */ + + //dfs public class prob4_graph { private int V; diff --git a/Graph/prob7_graph.java b/Graph/prob7_graph.java index 4c394ca..dbec404 100644 --- a/Graph/prob7_graph.java +++ b/Graph/prob7_graph.java @@ -32,7 +32,7 @@ void primsMst(int graph[][]) { for (int i = 0; i < V; i++) { key[i] = Integer.MAX_VALUE; mstSet[i] = false; - } + } // Always include first 1st vertex in MST. key[0] = 0; // Make key 0 so that this vertex is @@ -43,7 +43,6 @@ void primsMst(int graph[][]) { // Pick thd minimum key vertex from the set of vertices // not yet included in MST int u = findMinkey(key, mstSet); - mstSet[u] = true; // Update key value and parent index of the adjacent // vertices of the picked vertex. Consider only those diff --git a/Greedy/prob10_grdy$1.class b/Greedy/prob10_grdy$1.class new file mode 100644 index 0000000000000000000000000000000000000000..90c57686a2a62a434b038a22619f3fdc4f932074 GIT binary patch literal 807 zcmZ`%O;6iE5Ph4kCB`WsKp`!(w1i?OsA*0;1R#^hpOlPsH$TVQ7Z^byEFUtjc4A>{`vd!7l60u7~ptPMF~$0tYd@YnSlzPb8K?F z;CRVU+4DnR?=uuF`<$UPP-DrkF!V!toJ>YCIuoOS5bmnUm59izI$BQ7MUaqhI$fs5&I9ow!^Sv4KKyD=msM6x+kMc>FWM{BxP1leJ>O` zNsBnRPq{@B?FZdKR;$n|+It}LexJcORY~N^_kOCco-6!yS`aniUFZfX_CxPT>Q8FS zv1Ou#ZHBpH8S4)!)+VYjOuWJlhh@S>n_(sQr~fT5QA3@fmcQ&#+F9)k%NaDIgJC`w zNheS0Bk_4UhB@oPxo{l&kOt^dSqzO_e-2ebBP7AOWVaagbUM~EMTO@lF%7aEY|@M2 zAkp-sinK^Eo#x5gAj`;>+dsg*kwXuH_DTjeX(!3Fr_>e-S+KeL9fc098x+6JM6A~j zC}MFMu}%CmU9H{ujnXcy8H7!MSG2MK literal 0 HcmV?d00001 diff --git a/Greedy/prob10_grdy$ItemValue.class b/Greedy/prob10_grdy$ItemValue.class new file mode 100644 index 0000000000000000000000000000000000000000..6c213b931fc2badbc289dfa44f0e9af2d15fc576 GIT binary patch literal 508 zcmZ8d%TB^T6g|VMQi>>wFYt|uU5Kt+XxvDQO$aV9B(6+>i76?qX{p99;CoyU5>5O7 zKgxKfD|9jE-a9k*+;h+O&&L;la~$f(Vl9g~tSi`1P}Weyn+Jq zZ2GTCeLFCqBPURrVXRssIqcYO#7Wti+^{@P2G_0~hBExach?=r9{0=5uyDs(yiu)j z+`$fg%F@mh4+j#V^u>`9<4Bc^bcwnaiA7dzXmQVxIfXFG;|UUGg_txqi7E3F>4(a= wJocx^OrX8T1WUvXWQaPOb40aj9xHU?kY*&Y%(nzeyisu#yYXMT$edDt0R~@Mr~m)} literal 0 HcmV?d00001 diff --git a/Greedy/prob10_grdy.class b/Greedy/prob10_grdy.class new file mode 100644 index 0000000000000000000000000000000000000000..53333f8d32e7d902474cd15ba3e521b28f836488 GIT binary patch literal 1608 zcmaJ>-%s0C6#i~v?8I>)D|H(fKSCGUB>V_anl1#`+H{Px37JO4mhmv%Bo=i^?8tU# z^EjyzFB7kuwwI}U;IY~?jjG-F1NL9+zo;gy-Eo|iAgadkz1QcS^PO|PbMF1?)$?Nj zH?Se2ALA0DGJKeja9M_caTy;V79`1}J6w@*4p)PSBXORLW@OAFC1Fm&JVP+=XpJpi zZ)prl-Y_&PSLe2^*$m>cZs^V`gFl|wVi0m>jg$rox}j~f8WqjD$18P`gmyHi$RBk< z0`cwqc0QlD&2Vnh;nm$DZ*~+VEJ(OUI1R2F3>V|ug$I0(r|R6;No_ioZtP@TKk}y8 zvZ~se?qY|VmRXsf`+CQ!wP#&*a<`$`PEm6Muob+A^9*W_R_ske?&cyz(YrY>;ktq} zZYcN=83jx3pyHy0tb%2%kjGo5>DZ3Nn?=pJZ`SMq5vu`wq~K%RlyFNy4wPG{2bGLY zGAUIaXjO+HvR&v=If*LE;M>jyg$` z&zX%Tx42_k9pZcs$%avE{ykp*AJ=2IZBvzL!)%d?>Otsc>N6tUA?h{W$jbNxYYgL5 zNxji(LDmS8L#i61_SE7vJQiJbmIn$_e=L_ArPb=HuhC^Yi@!N^BHDws= zuyfiUgVc1r*QpiM_*tvOmV{4T&hIe9PT19rJ#$yOlOQ zJpL2D4S!lth2-%QjLoRR3;4=ORhXTkR~3%n-+U~v!`FY$yns+XLf_OPy?#;1YZt`YG7e0I28O1(m`5w=fFWaG@{D2A2H}oD-l5r?N>9xAz~x@s=RMz zl#VE(?2?p3p?zBJ9IPB7_&7jL4H7245p1qQC7jRd|y65o>McbLWxr1uk2xI{?v5dTF`LWKQ;iPwlAAYq99j6{A{ zOk}>oq68mfFA;r-J_Iq0_dO2LqB~b4n7s6dT=s|MQdtPcOXa@sg;H4zkCh6ZeEE&M z=E@(His6OTsp-*Y2xf#|AxDJg2m!xCIVst22Y8V}x{f)@?;2fOS$fv7LQY3IjErK8 lW|6q@kt|H>Vd@7T^~L}KB=LUhxQje-l%&r91wKXZ^nYL_bX@=d literal 0 HcmV?d00001 diff --git a/Greedy/prob10_grdy.java b/Greedy/prob10_grdy.java new file mode 100644 index 0000000..8f86656 --- /dev/null +++ b/Greedy/prob10_grdy.java @@ -0,0 +1,62 @@ +import java.util.Arrays; +import java.util.Comparator; +//fractional knapsak +public class prob10_grdy { + static class ItemValue { + Double cost; + double wt, val, ind; + + // item value function + public ItemValue(int wt, int val, int ind) { + this.wt = wt; + this.val = val; + this.ind = ind; + cost = new Double((double) val / (double) wt); + } + } + + private static double getMaxValue(int[] wt, int[] val, int capacity) { + ItemValue[] iVal = new ItemValue[wt.length]; + + for (int i = 0; i < wt.length; i++) { + iVal[i] = new ItemValue(wt[i], val[i], i); + } + + Arrays.sort(iVal, new Comparator() { + @Override + public int compare(ItemValue o1, ItemValue o2) { + return o2.cost.compareTo(o1.cost); + } + }); + + double totalValue = 0d; + for (ItemValue i : iVal) { + int curWt = (int) i.wt; + int curVal = (int) i.val; + + if (capacity - curWt >= 0) { + capacity = capacity - curWt; + totalValue += curVal; + } else { + double fraction = ((double) capacity / (double) curWt); + totalValue += (curVal * fraction); + capacity = (int) (capacity - (curVal * fraction)); + break; + } + } + return totalValue; + } + + // Driver code + public static void main(String[] args) { + int[] wt = { 10, 40, 20, 30 }; + int[] val = { 60, 40, 100, 120 }; + int capacity = 50; + + double maxValue = getMaxValue(wt, val, capacity); + + // Function call + System.out.println("Maximum value we can obtain = " + + maxValue); + } +} diff --git a/Greedy/prob11.class b/Greedy/prob11.class new file mode 100644 index 0000000000000000000000000000000000000000..249945bca54272db11ad177e9b7f65e2b7c30bb6 GIT binary patch literal 876 zcmZuv-A)rx5dKbgx7%))Qu>FstSkbul+uDGYAiHS5p9H4Q^JMZxTPyDw!2Nc7`g9L zcwvko>2?lZevIjve}tAGvCblX6AhV`{f&eTUe10LMn(frUFm` zxFR8jX;-KL%((ih1PQYu=0wah_}5I!bczg|wz$i{-?!@q!}ykI8Res9&1moFwFY_Q z7p7IOHuXls=r|05Rw}vpv8to*zuMMY9!$hF5ep(TD%8|Xiy^7)Z5`^b^?XCO4)Rr} zZCVEfH&LqEN9}!M({zi6T5Y?wx|(y5GGvU2Sd@{$5<~p|ovP*0QO%CJLUhWuqqgi$ z$0T+#vRIap!!kqc0=yf~%ZOlt`W;@y5ILt+sT~^o)KtuKnRfmO(R7Hcp*Kf>L;eiD zz0#=vxZ@ZE(T0Me-wjDgHeIQLYCe%AZ2$rz64C%M-{H zavlDD>Z`QfWrGx7FDmb#Qv3wrtP%-Uy6jgE!K{+5aBE#|&>Q^7a%ui~#Z48d7FSeK z9}uNuR>_?r(B)Wf@YAK|^XTm&LG~=snL`run1qIDEMkH7tkLeWxQ;w-&=bCib&~gR z8;@`YTPUDR{vF)KGi;!S2QaaTHt9Ebh$vOfKzb@7HlVJ3jDE63#JR{HNFov}E}TL5 wjd6BH&p$}FPY%a}CE~_WekhV$^RG{(KO=ZP&#)JI41p*}*rt?AUNe{f0eg 9 * m) { + System.out.println("Not possible"); + return; + } + + // Create an array to store digits of result + int[] res = new int[m]; + // deduct sum by one to account for cases later + // (There must be 1 left for the most significant + // digit) + s -= 1; + for (int i = m - 1; i > 0; i--) { + // If sum is still greater than 9, + // digit must be 9. + if (s > 9) { + res[i] = 9; + s -= 9; + } else { + res[i] = s; + s = 0; + } + } + + // Whatever is left should be the most significant + // digit + res[0] = s + 1; // The initially subtracted 1 is + // incorporated here + + System.out.print("Smallest number is "); + for (int i = 0; i < m; i++) + System.out.print(res[i]); + } + + // driver program + public static void main(String[] args) { + int s = 22, m = 3; + findSmallest(m, s); + } + +} diff --git a/Greedy/prob12_grdy.class b/Greedy/prob12_grdy.class new file mode 100644 index 0000000000000000000000000000000000000000..2bf6f9e3dbf3d1b4664de5df4df21be692dbc696 GIT binary patch literal 1422 zcmaJ=O>Yxd6g|%~_BfM??S>jiYzGHI89QJX(}oX+w8b>kl9N<&1VSw6vono{*fW-A zjGC_b5nV@>y6L7>DJU)cfG+z-y6C>)%-B*K1$FW6ynE-|bMLwDy}$lDd<)&0())4Yp;g%SfUpzpHhm?KCWB*Y60-nok=2f!n%XdAd8;*{{|M8``P{k@?$31Peo>^_5VoypFh&-V<#SEHF9K$zcFbIW{84r-43AX0G=UY7j+#xyB zBki_Z{+hyl%C}^%s^cy={>9N$^X|8Kve~_1FYnpkTlsb{@x1Njg}}L<+_P$~)0X}t z+wXAa`O@({Qk(U{>B$P530pl`Q9$bl^}9Tfw0SzK@KD2N!Gvl8OUF`e=efIQjSp?q z#JX(z?qFZTm%K*}*WDZT1&q4mSc6(udY;A3eweH<<`^BuSJK((THewqv3k0ZiO7k> z?ft&>9{A+d8XaSGawcPnn(TI)wr^E6tP5N|rSE;c2`v0S4vTzc(|lwRE?!ew1UHpd z0pAi*v>(vBL4?9@viJ(3n0bjvG5ZqAFAVWL(au7p&C=#Dg$0saKs>n2V}gJ9Cq_g^ zSy3~8>UW~b-E8IniMeQ2-FgubKOOz6hLH!#S}uElaxq)^ja72A%8!^Qt~3|TmDFzz zFhggw-+G}i^Y648{C*8}MGdJA)9TNx6$v|A3FTa5`b=Qsj!L?xq;7=?<_BTniBibFV$xv_W$S~%fN z?G2)jl|N|Wsq?Q8Yd%&3CzVXigS7^)2Z(k#RNN)TN{do9^ k@N8~jl}~a5YxL$r`5D~fS7#TWQ{orw=Og-Y`d7Hjca@DkWdHyG literal 0 HcmV?d00001 diff --git a/Greedy/prob12_grdy.java b/Greedy/prob12_grdy.java new file mode 100644 index 0000000..4e5a137 --- /dev/null +++ b/Greedy/prob12_grdy.java @@ -0,0 +1,192 @@ +/** + * Maximum Length Chain of Pairs + * You are given n pairs of numbers. In every pair, the first number is always + * smaller than the second number. A pair (c, d) can follow another pair (a, b) + * if b < c. Chain of pairs can be formed in this fashion. Find the longest + * chain which can be formed from a given set of pairs. + * Source: Amazon Interview | Set 2 + * For example, if the given pairs are {{5, 24}, {39, 60}, {15, 28}, {27, 40}, + * {50, 90} }, then the longest chain that can be formed is of length 3, and the + * chain is {{5, 24}, {27, 40}, {50, 90}} + * + * This problem is a variation of standard Longest Increasing Subsequence + * problem. Following is a simple two step process. + * 1) Sort given pairs in increasing order of first (or smaller) element. Why do + * not need sorting? Consider the example {{6, 8}, {3, 4}} to understand the + * need of sorting. If we proceed to second step without sorting, we get output + * as 1. But the correct output is 2. + * 2) Now run a modified LIS process where we compare the second element of + * already finalized LIS with the first element of new LIS being constructed. + * The following code is a slight modification of method 2 o + */ + +public class prob12_grdy { + // method 1 + int a; + int b; + + public prob12_grdy(int a, int b) { + this.a = a; + this.b = b; + } + + static int maxChainLength(prob12_grdy arr[], int n) { + int i, j, max = 0; + int mcl[] = new int[n]; + /* + * Initialize MCL (max chain length) + * values for all indexes + */ + for (i = 0; i < n; i++) + mcl[i] = 1; + + for (i = 1; i < n; i++) { + for (j = 0; j < i; j++) { + if (arr[i].a > arr[j].b && (mcl[i] < mcl[j] + 1)) { + mcl[i] = mcl[j] + 1; + + } + } + max = Math.max(max, mcl[i]); + } + return max; + } + + public static void main(String[] args) { + prob12_grdy arr[] = new prob12_grdy[] { + new prob12_grdy(5, 24), + new prob12_grdy(15, 25), + new prob12_grdy(27, 40), + new prob12_grdy(50, 60) }; + System.out.println("Length of maximum size chain is " + maxChainLength(arr, arr.length)); + } + + // method 2 + /** + * + * static class val + * { + * int first; + * int second; + * }; + * + * static class pair + * { + * int first, second; + * + * public pair(int first, int second) + * { + * this.first = first; + * this.second = second; + * } + * + * @Override + * public int hashCode() + * { + * final int prime = 31; + * int result = 1; + * result = prime * result + first; + * result = prime * result + second; + * return result; + * } + * + * @Override + * public boolean equals(Object obj) + * { + * if (this == obj) + * return true; + * if (obj == null) + * return false; + * if (getClass() != obj.getClass()) + * return false; + * + * pair other = (pair) obj; + * if (first != other.first) + * return false; + * if (second != other.second) + * return false; + * + * return true; + * } + * + * } + * + * static Map m = new HashMap<>(); + * + * // Memoisation function + * static int findMaxChainLen(val p[], int n, + * int prev, int pos) + * { + * + * // Check if pair { pos, prev } exists + * // in m + * if (m.containsKey(new pair(pos, prev))) + * { + * return m.get(new pair(pos, prev)); + * } + * + * // Check if pos is >=n + * if (pos >= n) + * return 0; + * + * // Check if p[pos].first is + * // less than prev + * if (p[pos].first <= prev) + * { + * return findMaxChainLen(p, n, prev, + * pos + 1); + * } + * + * else + * { + * int ans = Math.max(findMaxChainLen( + * p, n, p[pos].second, 0) + 1, + * findMaxChainLen( + * p, n, prev, pos + 1)); + * + * m.put(new pair(pos, prev), ans); + * return ans; + * } + * } + * + * // Function to calculate maximum + * // chain length + * static int maxChainLen(val p[], int n) + * { + * m.clear(); + * + * // Call memoisation function + * int ans = findMaxChainLen(p, n, 0, 0); + * return ans; + * } + * + * // Driver Code + * public static void main(String[] args) + * { + * int n = 5; + * val []p = new val[n]; + * for(int i = 0; i < n; i++) + * p[i] = new val(); + * + * p[0].first = 5; + * p[0].second = 24; + * + * p[1].first = 39; + * p[1].second = 60; + * + * p[2].first = 15; + * p[2].second = 28; + * + * p[3].first = 27; + * p[3].second = 40; + * + * p[4].first = 50; + * p[4].second = 90; + * + * // Function Call + * System.out.print(maxChainLen(p, n) + "\n"); + * } + * + */ + +} diff --git a/Greedy/prob13_grdy.java b/Greedy/prob13_grdy.java new file mode 100644 index 0000000..6fa8a52 --- /dev/null +++ b/Greedy/prob13_grdy.java @@ -0,0 +1,61 @@ +/** + * Maximize sum of consecutive differences in a circular array + * Given an array of n elements. Consider array as circular array i.e element + * after an is a1. The task is to find maximum sum of the difference between + * consecutive elements with rearrangement of array element allowed i.e after + * rearrangement of element find |a1 – a2| + |a2 – a3| + …… + |an – 1 – an| + + * |an – a1|. + * + * + * Input : arr[] = { 4, 2, 1, 8 } + * Output : 18 + * Rearrange given array as : { 1, 8, 2, 4 } + * Sum of difference between consecutive element + * = |1 - 8| + |8 - 2| + |2 - 4| + |4 - 1| + * = 7 + 6 + 2 + 3 + * = 18. + * + * Input : arr[] = { 10, 12, 15 } + * Output : 10 + * + * The idea is to use Greedy Approach and try to bring elements having greater + * difference closer. + * Consider the sorted permutation of the given array a1, a1, a2,…., an – 1, an + * such that a1 < a2 < a3…. < an – 1 < an. + * Now, to obtain the answer having maximum sum of difference between + * consecutive element, arrange element in following manner: + * a1, an, a2, an-1,…., an/2, a(n/2) + 1 + * We can observe that the arrangement produces the optimal answer, as all a1, + * a2, a3,….., a(n/2)-1, an/2 are subtracted twice while a(n/2)+1 , a(n/2)+2, + * a(n/2)+3,….., an – 1, an are added twice. + * Note – a(n/2)+1 This term is considered only for even n because for odd n, it + * is added once and subtracted once and hence cancels out. + * + * + * + */ + +public class prob13_grdy { + static int maxSum(int arr[], int n) { + int sum = 0; + + Arrays.sort(arr); + // Subtracting a1, a2, a3,....., a(n/2)-1, + // an/2 twice and adding a(n/2)+1, a(n/2)+2, + // a(n/2)+3,....., an - 1, an twice. + + for (int i = 0; i < n / 2; i++) { + sum -= (2 * arr[i]); + sum += (2 * arr[n - i - 1]); + } + return sum; + } + + // Driver Program + public static void main(String[] args) { + int arr[] = { 4, 2, 1, 8 }; + int n = arr.length; + System.out.println(maxSum(arr, n)); + } + +} diff --git a/Greedy/prob14_grdy.class b/Greedy/prob14_grdy.class new file mode 100644 index 0000000000000000000000000000000000000000..7e515e248946e3adb5abb59cfb2c3574573601ec GIT binary patch literal 659 zcmY+C%Wl(95QhH~J8>GEG^A-Mwo?eb5Ux>65sSoOfrJ#P1tgKk1{P4U-~o6T-hj)0Tu|ud%y`cC&-`=b@4vo&1MmQA6=+zjpoFD4T*9)~c{ z)L?0736%PN=%)h#rE_CXKz$S)cmne~e&{{Pf{~XzcSloJ)Z;g9EKuwWhmxxXlm%Jf zyvp2!*Li)&x|6!&qg^-tCktFZ6jTql`HnI;t90bX>tz9W~5rXzRF!Re=ltDX5=~cse@t#_73|b8?(| z0T+!jUM!yZ@uTiDnn`KNbAz71Lf+$iSwM>=H0360hx?<=chva8fC?c^@~rTy#V8ny zH@`r9WI~HPOL?(PkgG74=q*NtQ8R3_XZ2@rgFS&Y6tK>0gW~HHa_zsuBg!PPuGq@J zFyEnUn5QV1Z_%_2bNbRY%y?k-TK)IGe^?&~7IF_8G%2U5xXtVi8*ZY3EiB_6ENo*1 z_p!=frcSDi!cWwMXp+20>df&L2TR9|dbM9~*`J`8)+yA_D9+5+a>AzR0hJG_T*w_X F{{XKla6te7 literal 0 HcmV?d00001 diff --git a/Greedy/prob14_grdy.java b/Greedy/prob14_grdy.java new file mode 100644 index 0000000..858de93 --- /dev/null +++ b/Greedy/prob14_grdy.java @@ -0,0 +1,64 @@ +/** + * Given a paper of size, A x B. Task is to cut the paper into squares of any + * size. Find the minimum number of squares that can be cut from the paper. + * + * Input : 13 x 29 + * Output : 9 + * Explanation : + * 2 (squares of size 13x13) + + * 4 (squares of size 3x3) + + * 3 (squares of size 1x1)=9 + * + * Input : 4 x 5 + * Output : 5 + * Explanation : + * 1 (squares of size 4x4) + + * 4 (squares of size 1x1) + * + * + * + * We know that if we want to cut a minimum number of squares from the paper + * then we would have to cut the largest square possible from the paper first + * and the largest square will have the same side as the smaller side of the + * paper. For example, if the paper has the size 13 x 29, then the maximum + * square will be of side 13. so we can cut 2 square of size 13 x 13 (29/13 = + * 2). Now remaining paper will have size 3 x 13. Similarly, we can cut the + * remaining paper by using 4 squares of size 3 x 3 and 3 squares of 1 x 1. So a + * minimum of 9 squares can be cut from the Paper of size 13 x 29. + * + * + * + */ + +public class prob14_grdy { + // To swap two numbers + static void swap(int a, int b) { + int temp = a; + a = b; + b = temp; + } + + static int minimumSquare(int a, int b) { + + int result = 0, rem = 0; + if (a < b) { + swap(a, b); + } + // Iterate until small size side is + // greater then 0 + while (b > 0) { + result += a / b; + rem = a % b; + a = b; + b = rem; + } + return result; + + } + + // Driver code + public static void main(String[] args) { + int n = 13, m = 29; + System.out.println(minimumSquare(n, m)); + } +} diff --git a/Greedy/prob15_grdy.class b/Greedy/prob15_grdy.class new file mode 100644 index 0000000000000000000000000000000000000000..55f03bf17b76904b10c72424ed75663ad90fa905 GIT binary patch literal 1284 zcmaJ=T~8B16g|`K2dz~qxQe!mU;*2rEvQtJDk>F1Be0qRrXfa$?g|U-ZfzG$edZ@< z;*$@=glBzFV+=pQ|6qJG{so9w@3thAK+JAt?%v#U=bSTlzyJNZ1>ica`yoT|L&9kv z&Y-JJCitd$mx$}C?jQl_IsbtUta z@yK+R@8@3fa+N`jE@ZP=7k518@WSdeFYlELC2m>_r=tr~EBpmd7P+;Q%sCa)T1v;} zW%SCpz~Il>Yn6gAVY(*-%N2WZc;v}aMXx1XPylW41rWe-8Ib_`&`(8Uw(V4%3NKF^ z&a$mn+a(ON;bH($#AL(+7{n!pV=cW1v`;}>Trmm`L+25^7(5Hv1J$`&)iFxsjlD(~ zr76X9!hn!NP+1Ozxh)09k!IlhS z**(BT9mcrsC0)5!8T$5xnbr$?)!4JRNnwH)9J^AJF+$foW!tN3Wrjf3vW!Zm$g5R@ zc)e{sVXsHi*-38cMWfo+1f~xYX~`S_&eqDt5#_ChH*X=`>d0P;3@;XQremaKq!{`S z={t%WL-+sd&`UpnOrsBY!Q82$)lXk4?TmIY{u%581vELdN{wWU3TgHzc1wRjY_xdp z9aTeuzJZnSJ3LcUf+{>siHaE7KtvH$J^UWhCc5H^n20MvVgs@wri68oZPtG%LP}C3 z^*wsyij+u+w9+f+39YdyqP8y8H|sycilFNHt#vPf-ng_p4O(LeQhbRhB`F$02v-ro zH4M;?K8za}p>5Geu2lE5)>i4 zfv%764wCk-1ji?c>jLTcy|3c}84FAkj~R4BLk}L3hFMZIM{H+t5AzM43OsehAj&u? jyIkp}c5sfkb`so!Q@BFApSTW@3Bx!`52!Vx8ivq6TH-1m literal 0 HcmV?d00001 diff --git a/Greedy/prob15_grdy.java b/Greedy/prob15_grdy.java new file mode 100644 index 0000000..809a43c --- /dev/null +++ b/Greedy/prob15_grdy.java @@ -0,0 +1,88 @@ +/** + * Lexicographically smallest array after at-most K consecutive swaps + * Given an array arr[], find the lexicographically smallest array that can be + * obtained after performing at maximum of k consecutive swaps. + * + * + * + * Input: arr[] = {7, 6, 9, 2, 1} + * k = 3 + * Output: arr[] = {2, 7, 6, 9, 1} + * Explanation: Array is: 7, 6, 9, 2, 1 + * Swap 1: 7, 6, 2, 9, 1 + * Swap 2: 7, 2, 6, 9, 1 + * Swap 3: 2, 7, 6, 9, 1 + * So Our final array after k = 3 swaps : + * 2, 7, 6, 9, 1 + * + * Input: arr[] = {7, 6, 9, 2, 1} + * k = 1 + * Output: arr[] = {6, 7, 9, 2, 1} + * + * + * + * We strongly recommend that you click here and practice it, before moving on + * to the solution. + * Naive approach is to generate all the permutation of array and pick the + * smallest one which satisfy the condition of at-most k swaps. Time complexity + * of this approach is Ω(n!), which will definitely time out for large value of + * n. + * An Efficient approach is to think greedily. We first pick the smallest + * element from array a1, a2, a3…(ak or an) [We consider ak when k is smaller, + * else n]. We place the smallest element to the a0 position after shifting all + * these elements by 1 position right. We subtract number of swaps (number of + * swaps is number of shifts minus 1) from k. If still we are left with k > 0 + * then we apply the same procedure from the very next starting position i.e., + * a2, a3,…(ak or an) and then place it to the a1 position. So we keep applying + * the same process until k becomes 0. + * + */ + +public class prob15_grdy { + static void minimizeWithKSwaps(int arr[], int n, int k) { + + for (int i = 0; i < n - 1 && k > 0; ++i) { + // Set the position where we want + // to put the smallest integer + int pos = i; + for (int j = i + 1; j < n; ++j) { + // If we exceed the Max swaps + // then terminate the loop + if (j - i > k) + break; + // Find the minimum value from i+1 to + // max k or n + if (arr[j] < arr[pos]) + pos = j; + } + + // Swap the elements from Minimum position + // we found till now to the i index + int temp; + for (int j = pos; j > i; --j) { + temp = arr[j]; + arr[j] = arr[j - 1]; + arr[j - 1] = temp; + } + // Set the final value after swapping pos-i + // elements + k -= pos - i; + } + + } + + // Driver method + public static void main(String[] args) { + + int arr[] = { 7, 6, 9, 2, 1 }; + int n = arr.length; + int k = 3; + + minimizeWithKSwaps(arr, n, k); + + // Print the final Array + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + } + +} diff --git a/Greedy/prob1_grdy$1.class b/Greedy/prob1_grdy$1.class new file mode 100644 index 0000000000000000000000000000000000000000..0b6ece436f2cef459861191465e9643478fa083c GIT binary patch literal 732 zcmZuvO>fgc5PcITapSr;q$Mqd(r=M|K-3e5R7F(;B2root$N{rHufrP<*p-pQ_=s# z1qp%FL&cdNg*s~rL1`?_$3DODyxH-u-`6()USZQi8ILP)u;}86hZ3H;SaR{q#WJD1 zue34;1gEieMkuzEND_js((-tC(Ua+^=*5hPVUl!zV&8)n!8=KYX(-<+J6JH1{L-pnB{D zvCPc7Br`syQ1P*j4Z`f`1OI0B;UnPt`R~;pp*lV-VJ?Tpl(WK7A)z)%l{QD>^WBXq zd)JGN4-@C>*eyCzM+E9%g|}S>Z;$^3hmBS9$>VH^BXKNk{{VgEgfPwCl7WCd55V41 z*HFldy`66;?6O5)#`v}BA@i$u{7q)tW;5G6KjG}MeMfP;Bw%F^nN&axvw57uBaTJX WF^`2DspA31THd~n8CGB7Ge5T>(W3PL literal 0 HcmV?d00001 diff --git a/Greedy/prob1_grdy$Activity.class b/Greedy/prob1_grdy$Activity.class new file mode 100644 index 0000000000000000000000000000000000000000..05034020d0d8135706120a146bb69e59112921f7 GIT binary patch literal 364 zcmYLE%SyvQ6g`tilg4Ob>suEtT(ntO#DyCXq#y>QE|hL1kD*M7iOft3{VW$naN!5| zQR1C$vY2xpbI!T<{{DUc0Jycrb1q-AyrNF<(kx`bAA~8Q5832bZ!=l0F6Y@YWAGBmNC z4@V)oI1bT)7s7|f&~ND%_k|Wqp;shn(=e@TF2_}-6juzf@f=lIJsUmeb6(KOL2E&~ z4~A2m(`7E5Ytf@ogfP!Kvo-9`4KXC_k&%%)Br>uc XlG)g%o<(`Ii7^f+8cPQ;_Tm2nGgv?G literal 0 HcmV?d00001 diff --git a/Greedy/prob1_grdy.class b/Greedy/prob1_grdy.class new file mode 100644 index 0000000000000000000000000000000000000000..65d10173674c7a91130ed7d6e4a351860b2a6990 GIT binary patch literal 1527 zcmaJ>(QX?>6g`u*ckRuBP13ZG#I0#vYP)XSv_K(FLQ|KthB!rXDGGT&V|$ctv)-|G z#{s|d5AX^vJR%Tks#fI#`o#Aj0ll;9)Q%cqYiI7hf8TVDC(g!L-;G&w`8Geljo|943;fivv8duwb4=TfvbiL zPQ&*_Q1^Hkijcuvb$wT@GZ@9v1BOIhb_GLb%k{n{$?-e4hu(z)EYX~8!g2<`%T^-Wk~e6>oc6Dm`D78S3U0URa=VE?$tEj zZplH=5u2_)E;CNMq|pr1+agp=p(%w9W^sz7j6nsG`o4n?@S%kp4nD%i3>P+~=gDs= zf1bzkiFBR^A|DD*bd>1kS1hbJsA1K?8rB_r0;)vzmXs<~0q-}3dMLYL#>CAOHXPhS z-N9|FGR#gKeI#46`qaT0yiH=p`;>63_g?!EoqXgPDA%iQ1OXpXF%zK-Xs2?lJ~6%) zS1f|pWv|Zzu4E8ZZ6bGT7%I`DPRar0nTumwS^YwHjtVV!uSU!xGRNHvR@7dP`ZHHN zxjo5Ham|l4=mg<+ZEWHW-K-+3QI~#)tFK)3kSq%E6-hf?Y&1%*r)5Y+ z$I`3;4=mi(HU6BTFs_*EAIN<%x+rn>O=_nMh8CK1f48LEAM_c1oa8+Uiu-q$`(00j zg%~-i<>c*~V0J9<{;)4jfKT4vQGX`IjZ)OP=e1lVY8JK`F1{w{ByJ36{~t#$K!%r*XqBUx(VQ$Fg8fDY6`e*iavDhKTS>Nt{)zlw76_fvgBpC$Q&6=wV z&*3yH#xpoOscia?9-K--FA~YfPHNk() { + @Override + public int compare(Activity a1, Activity a2) { + return a1.end - a2.end; + } + }); + System.out.println( + "Following activities are selected :"); + int i = 0; + + System.out.print("(" + arr[i].start + ", " + + arr[i].end + "), "); + for (int j = 1; j < n; j++) { + if (arr[j].start >= arr[i].end) { + System.out.print("(" + arr[j].start + ", " + + arr[j].end + "), "); + + i = j; + } + } + + } + + public static void main(String[] args) { + int n = 6; + Activity arr[] = new Activity[n]; + arr[0] = new Activity(5, 9); + arr[1] = new Activity(1, 2); + arr[2] = new Activity(3, 4); + arr[3] = new Activity(0, 6); + arr[4] = new Activity(5, 7); + arr[5] = new Activity(8, 9); + + printMaxActivities(arr, n); + } +} diff --git a/Greedy/prob2_grdy.class b/Greedy/prob2_grdy.class new file mode 100644 index 0000000000000000000000000000000000000000..c5d99742cf7d71e96b5b6838e938c7d12f1eb4c1 GIT binary patch literal 1581 zcmaJ>-EJF26#i!Yv-Yx$H)+z+#*__BiygNyP3W(al-3YxaJm79R8ED^#yd&2S?^lA z>!5Jmhd|;AZgNd3r6r&~08h~CN=Q5aR}~P>tX=Go2(5O`nVECuobNkl=GVXXp98p# zWd$0>WW1w5!dMy^oEO8mf(y7P*4`CEE{!}UgjN_Lx1xggaAgP#(+U~CFXO6=YYcIV zyB>q|u)@Gx`bj2dY}XFw7-G5nGMSV;i!)@Zw#)Cgo2%SkGFKg1k=Jb3TCmA0o~sDU z6SdH6Y%Z9su0gzMirrJWht)^smRWR6cfD8(ecN3x3H#Jc!|8@nYF^uK@OfJtoN4*q z>eN^3zO_9m994|q6oVEW(hhB>xXc@&=c_o0VHJZIl5t(d4ct_53ndjZn3XZ7;x;}| zaR+zF_paxKLFk*U1s-mAR**@eoWh4HKEk|=k5$}5C52DK{8JTYaF#*orSUp=guqyR zMBy0*d!QZuYP z#2wnUgOE3A!)sIMk&d(N6&H!kkT~ULlg>_ahc~$!-Vrv36X?cJP{jfjTxSfYo8~4j zdv3!FAK2jrX+dbZVZdSYJQxx!k=1`d_7(o}yyrOH*VG5P9q3K! zfu`x`Zq!`5x288Xs8hJU=J`6ir5}OPJxRuWQLfJ!#(R~p-7RmEce|{EZQc~kvMpnY zdb{d*o9z~ZT5(6UCZIYc*n7Hl!U&OLyk+^Eq;u7|6O=p z_oGLYO~ ans = new Vector<>(); + for (int i = n - 2; i >= 0; i--) { + while (v >= deno[i]) { + v -= deno[i]; + ans.add(deno[i]); + } + } + + // Print result + for (int i = 0; i < ans.size(); i++) { + System.out.print( + " " + ans.elementAt(i)); + } + } + + // Driver code + public static void main(String[] args) { + int n = 93; + System.out.print( + "Following is minimal number " + + "of change for " + n + ": "); + findMin(n); + } + +} diff --git a/Greedy/prob3_grdy.class b/Greedy/prob3_grdy.class new file mode 100644 index 0000000000000000000000000000000000000000..951ea13f3c4e6b47ee451814c359827ddf2adce7 GIT binary patch literal 1681 zcmaJ?UsD@Z6#w01vp1|;pwM6`1w%_~!oS#7L7Q5YSR@!oYYxEpymd)%_595JNMjs?m6fF&hMOi_qTrzUjUfL zR~iP9<`~xy3*{9J3ep;`Vj|RB3y16B@cIDRPldbF;V`3N7P%h0fg2hIaB~0*Z)$i8 za~$&=Z!@TO49oEEGQ>04bq1wi*Caz<$*|;V(Abjhn%FW)lkjYFFO-?hVs@F~T*VjL zyDP$J?Q^_Cz71hm3`3dC(qpkFa;C8Axr*-^Ry`la)+%=3Zp%d@jMwM5_SUUOb+^`> z4Xt%tK#JkjmS^A_X70Xg*skF>9|STWhxSe+=0aeYHR*EP){(~@9q;06q5K*$2~0S_y|inidg3OSVsvf9IHCYxUb_PhLd;@ntj4i z(Xob4349kXh3@88-g+#zeTLX(k>Pw-U$lH#mo5X}6J{XGUx&mLvk_)G7I~sx)M^Z= zOk}eiHlKY+0Sxb6!||J~646?5Y|~`8kckHC*lSqF1_NWnS3~T|f^BUJf5Y&1Xy*CC z@;!#@XB`wdyHhgi4dFP_B4{&FkK>A-^5_(V5=#1Z+v>kCUxx1OGF7szIzx{mTu-*= zCzv=sj(RRad!_05vO$#C0g<0-V=?ToX)K>yq-YS1)Y^_ryYidBaAhs+1&y@frHPwV zW;sgUOH_j`R42nw0h}ghbYsX814355?0NW-bC9me~SI6=7i%~(~;55PPWlYdfaW1 zpq&r}VVV`gmwApy4A)NOcNR8=vH!QjIK4%K^iTnDdXVVi(>O${QId>gV)7Z-&orSn zrcrGvhtLyVO`3CNQ#H!B_FFl7sGO^N;tCP2tVdceKB0i_4)KuapTpCtV z>g*h!O7R1z``{bjtL(|qA5;5C{)p@}$(}=Kz&>8tXep2WoH?O3=*MN6jp7Ez=ye*UCutl@xI*{yD!#x3EM)L4vbaPZV~8J- znsbbB#5k1JH$shyzcD&Zd0%c(6Xso}ykjJD{pzn;HQuk5t4e>eTutzDRVB$2 pq = new PriorityQueue(); + // to store the 2 numbers formed by array elements to + // minimize the required sum + StringBuilder num1 = new StringBuilder(); + StringBuilder num2 = new StringBuilder(); + for (int x : a) { + pq.add(x); + } + + while (!pq.isEmpty()) { + num1.append(pq.poll() + ""); + if (!pq.isEmpty()) { + num2.append(pq.poll() + ""); + } + } + + long sum = Long.parseLong(num1.toString()) + Long.parseLong(num2.toString()); + return sum; + } + + // method 2 + static int minSum(int a[], int n) { + Arrays.sort(a); + + int n1 = 0; + int n2 = 0; + + for (int i = 0; i < n; i++) { + if (i % 2 == 0) { + n1 = n1 * 10 + a[i]; + } else { + n2 = n2 * 10 + a[i]; + } + } + + return num2 + num1; + + } + + public static void main(String[] args) { + int arr[] = { 6, 8, 4, 5, 2, 3 }; + System.out.println("The required sum is " + solve(arr)); + } +} diff --git a/Greedy/prob4_grdy.class b/Greedy/prob4_grdy.class new file mode 100644 index 0000000000000000000000000000000000000000..7699e4b183d57dcd7c125c87be5888a07581a4dd GIT binary patch literal 794 zcmY*X+m6yu6kUg&w$Q1}#DS`#j5A)j40LXSBO_*FGA0C+1TzWY!4#<25n57;3GdDy z_~^S&KInrIW99?=4!^?0%WjWv-at?UtdlElyFahhHDD0~EnjqT43QkIScwZoDJh+-y?Kij zjc1dRo}*>X$Wn>Fme{-B-!=Z8Y9fK^YEYjCM}d^Lut0OxutR^yHu5y<6lE%i{6w6y zA6P|<*44A_4n(R09?4%9T0#Q6(c(&@B_<#>T2cbhM(r#@EKfiUV(}oh)Trl9D<5$_ kw~;!TVfhmhbE_H&17$kkK8m=HJydXr2h?_r_z2ej02+{tKL7v# literal 0 HcmV?d00001 diff --git a/Greedy/prob4_grdy.java b/Greedy/prob4_grdy.java new file mode 100644 index 0000000..0c40b19 --- /dev/null +++ b/Greedy/prob4_grdy.java @@ -0,0 +1,64 @@ + +/** + * Minimum sum of absolute difference of pairs of two arrays + * + * + * Given two arrays a[] and b[] of equal length n. The task is to pair each + * element of array a to an element in array b, such that sum S of absolute + * differences of all the pairs is minimum. + * Suppose, two elements a[i] and a[j] (i != j) of a are paired with elements + * b[p] and b[q] of b respectively, + * then p should not be equal to q. + * + * + * Input : a[] = {3, 2, 1} + * b[] = {2, 1, 3} + * Output : 0 + * Explanation : + * 1st pairing: |3 - 2| + |2 - 1| + |1 - 3| + * = 1 + 1 + 2 = 4 + * 2nd pairing: |3 - 2| + |1 - 1| + |2 - 3| + * = 1 + 0 + 1 = 2 + * 3rd pairing: |2 - 2| + |3 - 1| + |1 - 3| + * = 0 + 2 + 2 = 4 + * 4th pairing: |1 - 2| + |2 - 1| + |3 - 3| + * = 1 + 1 + 0 = 2 + * 5th pairing: |2 - 2| + |1 - 1| + |3 - 3| + * = 0 + 0 + 0 = 0 + * 6th pairing: |1 - 2| + |3 - 1| + |2 - 3| + * = 1 + 2 + 1 = 4 + * Therefore, 5th pairing has minimum sum of + * absolute difference. + * + * Input : n = 4 + * a[] = {4, 1, 8, 7} + * b[] = {2, 3, 6, 5} + * Output : 6 + * + */ + +import java.util.*; + +public class prob4_grdy { + static long findMinSum(long a[], long b[], long n) { + // Sort both arrays + Arrays.sort(a); + Arrays.sort(b); + + // Find sum of absolute differences + long sum = 0; + for (int i = 0; i < n; i++) + sum = sum + Math.abs(a[i] - b[i]); + + return sum; + } + + // Driver code + public static void main(String[] args) { + // Both a[] and b[] must be of same size. + long a[] = { 4, 1, 8, 7 }; + long b[] = { 2, 3, 6, 5 }; + int n = a.length; + System.out.println(findMinSum(a, b, n)); + } +} diff --git a/Greedy/prob5_grdy.java b/Greedy/prob5_grdy.java new file mode 100644 index 0000000..2ad0cc6 --- /dev/null +++ b/Greedy/prob5_grdy.java @@ -0,0 +1,51 @@ +/** + * You are given a list of N coins of different denominations. You can pay an + * amount equivalent to any 1 coin and can acquire that coin. In addition, once + * you have paid for a coin, we can choose at most K more coins and can acquire + * those for free. The task is to find the minimum amount required to acquire + * all the N coins for a given value of K. + * + * + * + */ + +public class prob5_grdy { + + // Converts coin[] to prefix sum array + static void preprocess(int[] coin, int n) { + + // sort the coins value + Arrays.sort(coin); + + // Maintain prefix sum array + for (int i = 1; i <= n - 1; i++) + coin[i] += coin[i - 1]; + } + + // Function to calculate min cost when we + // can get k extra coins after paying + // cost of one. + static int minCost(int[] coin, int n, int k) { + + // calculate no. of coins needed + int coins_needed = (int) Math.ceil(1.0 + * n / (k + 1)); + + // return sum of from prefix array + return coin[coins_needed - 1]; + } + + // Driver Code + static public void main(String[] args) { + int[] coin = { 8, 5, 3, 10, 2, 1, 15, 25 }; + int n = coin.length; + + preprocess(coin, n); + + int k = 3; + System.out.println(minCost(coin, n, k)); + + k = 7; + System.out.println(minCost(coin, n, k)); + } +} diff --git a/Greedy/prob6.java b/Greedy/prob6.java new file mode 100644 index 0000000..b78701b --- /dev/null +++ b/Greedy/prob6.java @@ -0,0 +1,55 @@ +public class prob6 { + static int maxLevel(int[] boxes, int n) { + + // Sort objects in increasing order + // of widths + Arrays.sort(boxes); + + int ans = 1; // Initialize result + + // Total width of previous level + // and total number of objects in + // previous level + int prev_width = boxes[0]; + int prev_count = 1; + + // Number of object in current + // level. + int curr_count = 0; + + // Width of current level. + int curr_width = 0; + for (int i = 1; i < n; i++) { + // Picking the object. So + // increase current width + // and number of object. + curr_width += boxes[i]; + curr_count += 1; + + // If current width and + // number of object + // are greater than previous. + if (curr_width > prev_width && + curr_count > prev_count) { + + // Update previous width, + // number of object on + // previous level. + prev_width = curr_width; + prev_count = curr_count; + + // Reset width of current + // level, number of object + // on current level. + curr_count = 0; + curr_width = 0; + + // Increment number of + // level. + ans++; + } + } + + return ans; + } +} diff --git a/Greedy/prob7_grdy.class b/Greedy/prob7_grdy.class new file mode 100644 index 0000000000000000000000000000000000000000..e15fc61d20b334c5e1625d28365deef2b89a67a3 GIT binary patch literal 977 zcmZ8fOHUI~7(KT$bMJIIrMxckMsQPTX^k;MBE*hzU46(&h#anKai(c)XTihmum)*y?Mw!8m z7c%OkV>-hS&DGuYhfD5Gpc5FO9%Z*wVHk)P7Ps6-ZhG6TY^HPdTB))*uijzhs*T#Z zce|we#&&Ae;@sM1ZDTK`)HVc6fl(V{7`G9DEihr@A|`3!xt5{(ymz*^<*nBlLIpDP z7oOYOt$Soyt2T(09XF+F`Yu_ilOfM7&olG|jsArh#Euee(?0ZgW_ksalpLox0S&~$ zq-U6BV^kScW9A*$2@S|5J$V2s3GIN!BxNsXX_UBcn!`0mXpX5lVHqAfMz7>EGMswg z@cl4r`9A_&>WUDFfDi%ky+as^Fp~jc{vkBS(wvCq*wpe6J<^i;AuJh@#t{tdwd7J9 zAu5G5kH94lfF_0rH=Ab;s8?#k;Vu6Y$+#j(tw?fV?OTczE&o`WQZ)USRCv=rP);KI z5k;CU|0!)S6hyF!0U8^$b%9>WYlP|~F$s#~D%ES~!Y#zGL^X#V+$Yrd%IxW1AVM} zbd)T{(B1h;cuqD2884V0t-QvwdELn74LzIZbPGMZ$Q3RKC(bakOG3?w)9E${C*5+Q z?dZw2W6ZW4{sy5$a#rfnko-Ngx6sdjlPSstn86^W5=RmXNZ|(3l*?t@!4<4hQjD@u HnfCq$`@^oe literal 0 HcmV?d00001 diff --git a/Greedy/prob7_grdy.java b/Greedy/prob7_grdy.java new file mode 100644 index 0000000..c8da911 --- /dev/null +++ b/Greedy/prob7_grdy.java @@ -0,0 +1,54 @@ +public class prob7_grdy { + public static int maxSum(int stack1[], int stack2[], + int stack3[], int n1, int n2, + int n3) { + int sum1 = 0, sum2 = 0, sum3 = 0; + // Finding the initial sum of stack1. + for (int i = 0; i < n1; i++) + sum1 += stack1[i]; + // Finding the initial sum of stack2. + for (int i = 0; i < n2; i++) + sum2 += stack2[i]; + + // Finding the initial sum of stack3. + for (int i = 0; i < n3; i++) + sum3 += stack3[i]; + + int top1 = 0, top2 = 0, top3 = 0; + int ans = 0; + while (true) { + // If any stack is empty + if (top1 == n1 || top2 == n2 || top3 == n3) + return 0; + + // If sum of all three stack are equal. + if (sum1 == sum2 && sum2 == sum3) + return sum1; + + // Finding the stack with maximum sum and + // removing its top element. + if (sum1 >= sum2 && sum1 >= sum3) + sum1 -= stack1[top1++]; + else if (sum2 >= sum1 && sum2 >= sum3) + sum2 -= stack2[top2++]; + else if (sum3 >= sum2 && sum3 >= sum1) + sum3 -= stack3[top3++]; + } + + } + + /* Driver program to test above function */ + public static void main(String[] args) { + int stack1[] = { 3, 2, 1, 1, 1 }; + int stack2[] = { 4, 3, 2 }; + int stack3[] = { 1, 1, 4, 1 }; + + int n1 = stack1.length; + int n2 = stack2.length; + int n3 = stack3.length; + + System.out.println(maxSum(stack1, stack2, + stack3, n1, n2, n3)); + } + +} diff --git a/Greedy/prob8_grdy.class b/Greedy/prob8_grdy.class new file mode 100644 index 0000000000000000000000000000000000000000..49cf4d3b93d70a35fa70d556ca3e7d3ba01852ad GIT binary patch literal 2477 zcmcIm-%}G;6#g#RWRti`1f!;ajTSW|l=!RE62xK@#RjzoML=se*##DoY)m#PwteFt z=u$@(Xq-}#H?HO8Lsugo)Wm3--sPVR5;0=r|gjr|IGX+D{Cn9+PnCf8Nai#bE@eLctCBV3KSL%QdEgd~`?Yn8k? zX328fTYC@4$~5#~pN74NXm|@<8oH(U7*_>CXKdT4Iu*Sq!LmzLxw~CqI(=@2)Ty;~AjtvGyh)F6Y`nRdJ57Ndty(8^XMyHL z$tZ7(>?R3ZP-K^@j#;FEU6b(|8(MbqisU~zXX-^B)H3c6C=nIdQ`DEtv|Y;U&XnaW za8`BnlEWgxv9vpvCSNxix;Z3MsgqZFxj=PsT&=Gcn6yVXc)B;)ZGbNx{J$?YwtTa%yA93AX}wU$T8>E) z_Pz#ABiTk%$2Q>k`v0%G3DT?!rH#(IRR69(#pePCUn^p(jtJ~~vmN&H^zPw{S08!#arE*{;;l&eHox|B6jB>sgZPOPfhc7VZItgq!2mV9tSF`VF!c(@UD7<> z^#pD4?kDiXd!9gPdGF>Xz!6#=Wje>O1IN*c6V&nIVgyDKajpib`984jq)o+oAC}H*ZH|UY0G8yrP zRhMPkwMPi7sOyi`e_!#5N9&Ix-XUMa_i|A64En?Vu=HtOC0(OUjDtpHmMVTa`(gaEMmm6 z5AkLvek5SB$-Q@sNKK{Q=ySmee|UfExFaOzPmud$bwkKW8U# IhO6m+0DNO%`v3p{ literal 0 HcmV?d00001 diff --git a/Greedy/prob8_grdy.java b/Greedy/prob8_grdy.java new file mode 100644 index 0000000..a3bb606 --- /dev/null +++ b/Greedy/prob8_grdy.java @@ -0,0 +1,163 @@ + +/** + * + * Given an array of jobs where every job has a deadline and associated profit + * + * + * + * if the job is finished before the deadline. It is also given that every job + * takes a single unit of time, so the minimum possible deadline for any job is + * 1. How to maximize total profit if only one job can be scheduled at a time. + * + * Input: Four Jobs with following + * deadlines and profits + * JobID Deadline Profit + * a 4 20 + * b 1 10 + * c 1 40 + * d 1 30 + * Output: Following is maximum + * profit sequence of jobs + * c, a + * + * + * Input: Five Jobs with following + * deadlines and profits + * JobID Deadline Profit + * a 2 100 + * b 1 19 + * c 2 27 + * d 1 25 + * e 3 15 + * Output: Following is maximum + * profit sequence of jobs + * c, a, e + * + * + * + */ +import java.util.*; + +public class prob8_grdy { + char id; + int deadline, profit; + + public prob8_grdy() { + } + + public prob8_grdy(char id, int deadline, int profit) { + this.id = id; + this.deadline = deadline; + this.profit = profit; + } + + void printJobScheduling(ArrayList arr, int t) { + // Length of array + int n = arr.size(); + // Sort all jobs according to decreasing order of + // profit + Collections.sort(arr, (a, b) -> b.profit - a.profit); + // To keep track of free time slots + boolean result[] = new boolean[t]; + // To store result (Sequence of jobs) + char job[] = new char[t]; + + for (int i = 0; i < n; i++) { + // Find a free slot for this job (Note that we + // start from the last possible slot) + for (int j = Math.min(t - 1, arr.get(i).deadline - 1); j >= 0; j--) { + if (result[j] == false) { + result[j] = true; + job[j] = arr.get(i).id; + break; + } + } + + } + + // Print the sequence + for (char jb : job) + System.out.print(jb + " "); + System.out.println(); + } + + // method 2 optimised using maxheap (nlogn) + // a class to represent job + static class Job { + char job_id; + int deadline; + int profit; + + Job(char job_id, int deadline, int profit) { + this.deadline = deadline; + this.job_id = job_id; + this.profit = profit; + } + } + + static void printJobScheduling(ArrayList arr) { + int n = arr.size(); + // sorting the array on the + // basis of their deadlines + Collections.sort(arr, (a, b) -> { + return a.deadline - b.deadline; + }); + + for (int i = n - 1; i > -1; i--) { + int slots_available = 0; + + if (i == 0) { + slots_available = arr.get(i).deadline; + } else { + slots_available = arr.get(i).deadline - arr.get(i - 1).deadline; + } + + // include the profit of job(as priority), + // deadline and job_id in maxHeap + maxHeap.add(arr.get(i)); + + while (slot_available > 0 + && maxHeap.size() > 0) { + + // get the job with max_profit + Job job = maxHeap.remove(); + + // reduce the slots + slot_available--; + + // include the job in the result array + result.add(job); + } + } + + // jobs included might be shuffled + // sort the result array by their deadlines + Collections.sort(result, (a, b) -> { + return a.deadline - b.deadline; + }); + for (Job job : result) { + System.out.print(job.job_id + " "); + } + System.out.println(); + } + + // Driver code + public static void main(String args[]) { + ArrayList arr = new ArrayList(); + arr.add(new prob8_grdy('a', 2, 100)); + arr.add(new prob8_grdy('b', 1, 19)); + arr.add(new prob8_grdy('c', 2, 27)); + arr.add(new prob8_grdy('d', 1, 25)); + arr.add(new prob8_grdy('e', 3, 15)); + + // Function call + System.out.println( + "Following is maximum profit sequence of jobs"); + + prob8_grdy job = new prob8_grdy(); + + // Calling function + job.printJobScheduling(arr, 3); + } + +} diff --git a/Greedy/prob9_grdy.java b/Greedy/prob9_grdy.java new file mode 100644 index 0000000..b1af104 --- /dev/null +++ b/Greedy/prob9_grdy.java @@ -0,0 +1,60 @@ +/** + * + * Every positive fraction can be represented as sum of unique unit fractions. A + * fraction is unit fraction if numerator is 1 and denominator is a positive + * integer, for example 1/3 is a unit fraction. Such a representation is called + * Egyptian Fraction as it was used by ancient Egyptians. + * Following are few examples: + * + * + * Egyptian Fraction Representation of 2/3 is 1/2 + 1/6 + * Egyptian Fraction Representation of 6/14 is 1/3 + 1/11 + 1/231 + * Egyptian Fraction Representation of 12/13 is 1/2 + 1/3 + 1/12 + 1/156 + * + * + * We can generate Egyptian Fractions using Greedy Algorithm. For a given number + * of the form ‘nr/dr’ where dr > nr, first find the greatest possible unit + * fraction, then recur for the remaining part. For example, consider 6/14, we + * first find ceiling of 14/6, i.e., 3. So the first unit fraction becomes 1/3, + * then recur for (6/14 – 1/3) i.e., 4/42. + * Below is implementation of above idea + * + * + */ + +public class prob9_grdy { + static void printEgyptian(int nr, int dr) { + if (dr == 0 || nr == 0) { + return; + } + + // If numerator divides denominator, + // then simple division makes + // the fraction in 1/n form + if (dr % nr == 0) { + System.out.print("1/" + dr / nr); + return; + } + + // If denominator divides numerator, + // then the given number is not fraction + if (nr % dr == 0) { + System.out.print(nr / dr); + return; + } + + // If numerator is more than denominator + if (nr > dr) { + System.out.print(nr / dr + " + "); + printEgyptian(nr % dr, dr); + return; + } + + // We reach here dr > nr and dr%nr + // is non-zero. Find ceiling of + // dr/nr and print it as first + // fraction + + int n = dr / nr + 1; + } +} diff --git a/Heap&Hashing/aindex.txt b/Heap&Hashing/aindex.txt new file mode 100644 index 0000000..70679c2 --- /dev/null +++ b/Heap&Hashing/aindex.txt @@ -0,0 +1,15 @@ +1.Choose k array elements such that difference of maximum and minimum is +2.Top k most frequent elements +3.Kth smallest and largest +4.Find the maximum repeating number in O(n) time and O(1) extra space +5.to find maximum length of sub array having sum 0 +6.Sliding Window Maximum (Maximum of all subarrays of size k) +7.Sum of minimum and maximum elements of all subarrays of size k. +8.K’th largest element in a stream +9.Count distinct elements in every window of size k +10.Find Recurring Sequence in a Fraction +11.Length of the largest subarray with contiguous elements +12.Find Itinerary from a given list of tickets +13.Subarrays with distinct elements(*) +14.majority element + diff --git a/Heap&Hashing/prob10.class b/Heap&Hashing/prob10.class new file mode 100644 index 0000000000000000000000000000000000000000..494b8030bef33e520fc508eee675af508453e864 GIT binary patch literal 1789 zcmaJ>ZBr9h6n<_4NImx=}wTqYSFGcx>z?P zShVKYrAtc}WoZqg7-JyL!#+~oGt6X$yA>+0;Y*BZ_zE{PtRb!8CT?k1$8G7$FvQku z+jBjK*Yd)v*gNh}7}*H!Xt;}ey9se7Ya5tJj7N6+p_K>(zHpR@ZV{(QF-qtBy3c-EsunB?}`KBGuNSI6JUA%Yr;2$RrV_WnPzFN)d~1YkKi8Z-7bmK z>zGwM27v__V;HUSJ(0F8oqOAcS0T&wxaGO;!L}|)2S&@&*=@^3yvu@kpYOrDGrZL| zL&UJWEvX1ZWj$*^kp46<5W4Uh>{l`v#%T@v z&ILr|qb6I1zNOSK{eOxF^1q|+@oNMNiw%UvCu*r+BKRC@i;3VN!VM@dkZRfs4Mcob z|8^o6Q!6rX!c2u05}`w=M~DJ>@=$@7|NNN)(#je1;|!)-z3&oSkizC;k(Kc3#N;7jg~fQ_7YzP};ds1(Q!g<@ z=Hd~dgSJx2Cc|-GwEGCrT#TYfNSh?-7UqbHM2;eGj7i1_J4$Vw^%FnBxAa#D{TrhC Sl=NSq{UDWGB;Q4Uz4k9ha< mp = new HashMap<>(); + mp.clear(); + + int rem = numr % denr; + + while ((rem != 0) && (!mp.containsKey(rem))) { + mp.put(rem, res.length()); + + rem = rem * 10; + int result_part = rem / denr; + res += String.valueOf(result_part); + rem = rem % denr; + } + + if (rem == 0) + return ""; + else if (mp.containsKey(rem)) + return res.substring(mp.get(rem)); + + return ""; + + } + + public static void main(String[] args) { + int numr = 8, denr = 3; + String res = fractionToDecimal(numr, denr); + if (res == "") + System.out.print("No recurring sequence"); + else + System.out.print("Recurring sequence is " + + res); + } +} diff --git a/Heap&Hashing/prob11.class b/Heap&Hashing/prob11.class new file mode 100644 index 0000000000000000000000000000000000000000..189535f37fb3e928c825c052ac023305bde39ff0 GIT binary patch literal 1506 zcmaJ>-%}e^6#j0q*&CLnq}BxyLZbyuQXxev0s+)UDXF12lPZI}^pae{md$P^d&3l; z>x)m0Px|Kcr4RaIA6lk5{R8}yd?=o~ixQ?CGm~@AIrsed&N+L}UoW0L2k;SYTeyI6 zjtL71j9bWJQgfFz$ys;{Z)2G*IXTRu+t58=jLX$rHx@^7%oO$J>`0(brJ5@ zrQ*0|V-D}z_yE^!e2D8D^EOq#U}F&r97{IJShjHquQOzB1c3@wS9CU{+7FuHu!)s4 zR&9KYPdGlcaRU`9JI+k@XDBy!@5zQ@NbFE)F^&j*)mO45yA1qLcs;qfr^~Ar`szEi zC{q_jv&rD(`!3_K<-#`%=|QBgU;Vkcl&^=AIb>C9?YSh_eTiibfu6`6M*(S4~ zM-ZJjz8jRjq|PepuN3XFh0pLg!)!dJT(Fl@`!eSReoKZbr*pflUeF73VQ*J-yW%M4 zhB?MC+7<`068H_Fwp_JOT&RSv2&Hqr&eJ(ET#C@2Pfz{nXfPg?ajpUXO`l^;kKq=> z)LHeee;6Fd(@!J@u_hWS=pJ#@Xi&8vIOug4?5gj}Zp9N}C<)n5{VhI?5l?(w_)SlS zQ?X;YZxW|K`ZVVp?;LgHE6n>povGqeu-}Pc&`;Zplw(Niw?I6ZvMjl#>F&qk^JQZtxtbj}nh){a zA4qIJMRLg)Gm6>SV;E16+9GZ~rHPp}?#^?Ek3Ym$WZ>}F!u%QLBUJh{sVzr49D~oN z95Xgd&zp|vq?!)THh;nJL?jq@kC9$^kYtZeevRn26TcCvM1*@SDr%gNP9TLzD)}-- zk;4^gzzop^T3|OZjaw*S3q=UpU>-`ik85~9_urGx540W}iZ}!F1vq2ugbdRhBgAqf zhytUFClud^mB8O53{avs;#N^ug8%`G8UClWoy=I9+eXIT+)im?YLRP_&J1pDXS7^< zjDf4iu%2NMcmn%u5+f8Egu6g1Y6eTRwP;n*no43Us`^b->9i>EO?-iM(!NV_n&dqF G3;zI?+*#@X literal 0 HcmV?d00001 diff --git a/Heap&Hashing/prob11.java b/Heap&Hashing/prob11.java new file mode 100644 index 0000000..cd174ca --- /dev/null +++ b/Heap&Hashing/prob11.java @@ -0,0 +1,60 @@ + +/** + * Length of the largest subarray with contiguous elements + * + * Input: arr[] = {10, 12, 11}; + * Output: Length of the longest contiguous subarray is 3 + * + * Input: arr[] = {10, 12, 12, 10, 10, 11, 10}; + * Output: Length of the longest contiguous subarray is 2 + * + * The idea is similar to previous post. In the previous post, we checked + * whether maximum value minus minimum value is equal to ending index minus + * starting index or not. Since duplicate elements are allowed, we also need to + * check if the subarray contains duplicate elements or not. For example, the + * array {12, 14, 12} follows the first property, but numbers in it are not + * contiguous elements. + * To check duplicate elements in a subarray, we create a hash set for every + * subarray and if we find an element already in hash, we don’t consider the + * current subarray. + * Following is the implementation of the above idea + * + */ +import java.util.*; + +public class prob11 { + static int findLength(int arr[]) { + int n = arr.length; + int max_len = 1; + + for (int i = 0; i < n - 1; i++) { + HashSet set = new HashSet<>(); + set.add(arr[i]); + int mn = arr[i], mx = arr[i]; + + for (int j = i + 1; j < n; i++) { + if (set.contains(arr[j])) + break; + + // Else add current element to hash set and update + // min, max if required. + set.add(arr[j]); + mn = Math.min(mn, arr[i]); + mx = Math.max(mx, arr[j]); + + // We have already checked for duplicates, now check + // for other property and update max_len if needed + if (mx - mn == j - i) + max_len = Math.max(max_len, mx - mn + 1); + } + } + return max_len; // Return result + + } + + public static void main(String[] args) { + int arr[] = { 10, 12, 12, 10, 10, 11, 10 }; + System.out.println("Length of the longest contiguous subarray is " + + findLength(arr)); + } +} diff --git a/Heap&Hashing/prob12.class b/Heap&Hashing/prob12.class new file mode 100644 index 0000000000000000000000000000000000000000..38a8d683d34b1a581909a1dd5313c674adf02ade GIT binary patch literal 2043 zcmaJ?O;;OL7=CU7nIRc0gs);1sn8noK?=1N8bl>PNl8-LAlTNgNw|`M$xO^lII{B` z&vD^WH|oNL8#6lQDB7{jKLm0;;F-%FA4nf8h39pFxs=&;MVYUm`kdiSM#H*MWn%BbQ zGcA^jGL~d4%eXFMMMfrwXK_Qqs)Q^Jb-bxy1DgzeEhxdpmkhhM&(P`4O2#mFEv>7T#VrMI z35y=b!c&HVJJ?ik7xxsrjdvuxtKdDnPd&;Qd#bK&jb@B$-IhS<6;V>K1!_;vf@#{8 zT~n($ZkNq1>r4P2$k(!o^vNvs?CRkk+pv< z2ixGs9?3>3t5%+WL>`HCcZqd|v*j_br=OD6%Oc4>ZGQW^zs33nDL9E0k-KJMC(! z*SS18@wY9IOL;+GKNZGs@w7Bf78JxTbZQ1m%(M6?!%#)tsrII3mr1g0)v&Fn z8uXtx%-bLrL{xHemQWGwt1^tYIIbCc<}P<{Y%}h%S|YOSOCZ7ovZlFPCzCI|<+w&o zX0NEmmd>s5Ci0X^?V zIXy>jE#LjP?jOnPTG6)BYbxrz@Lpa z(816^CqpjYpp(W|m>@x7cmz2gOEl0W#2^VFM`%FtWAotX50>*7=V{+DPLj|xzSa>N z?r^Lc==R}j^twy(mODV;;OO`GuTZ|nGvPD$(Q_E3u)RJJE1&oUqoj`~9)doX`{+yL zqU6`zJvjPPROxf7%%hLwDE(1!yo3Z^r++MsOIX4*I4+}(m+>*K;1l}xKE*6Pqwni; zr0@kHzrh>$77O@}EDo`VpRtS=$=ev@C+L?jCSm+BCZC{NLXhOC$M7kC2{AZ|3r-3b z(M4e+)M{}O8nxF)^XzeZW8wbrK(k}9@L+i8SUelXMI;W4IjXf`JcVVwma!=@`|>u<#FM{`~y_ literal 0 HcmV?d00001 diff --git a/Heap&Hashing/prob12.java b/Heap&Hashing/prob12.java new file mode 100644 index 0000000..f0e8cae --- /dev/null +++ b/Heap&Hashing/prob12.java @@ -0,0 +1,83 @@ +import java.util.HashMap; +import java.util.Map; + +/** + * Find Itinerary from a given list of tickets + * + * + * Input: + * "Chennai" -> "Banglore" + * "Bombay" -> "Delhi" + * "Goa" -> "Chennai" + * "Delhi" -> "Goa" + * + * Output: + * Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore, + * + * 1) Create a HashMap of given pair of tickets. Let the created + * HashMap be 'dataset'. Every entry of 'dataset' is of the form + * "from->to" like "Chennai" -> "Banglore" + * + * 2) Find the starting point of itinerary. + * a) Create a reverse HashMap. Let the reverse be 'reverseMap' + * Entries of 'reverseMap' are of the form "to->form". + * Following is 'reverseMap' for above example. + * "Banglore"-> "Chennai" + * "Delhi" -> "Bombay" + * "Chennai" -> "Goa" + * "Goa" -> "Delhi" + * + * b) Traverse 'dataset'. For every key of dataset, check if it + * is there in 'reverseMap'. If a key is not present, then we + * found the starting point. In the above example, "Bombay" is + * starting point. + * + * 3) Start from above found starting point and traverse the 'dataset' + * to print itinerary. + * + */ + +public class prob12 { + private static void printResult(Map dataset) { + Map reverseMap = new HashMap(); + + for (Map.Entry entry : dataset.entrySet()) { + reverseMap.put(entry.getValue(), entry.getKey()); + } + + String start = null; + + for (Map.Entry entry : dataset.entrySet()) { + if (!reverseMap.containsKey(entry.getKey())) { + start = entry.getKey(); + break; + } + } + + if (start == null) { + System.out.println("Invalid Input"); + return; + } + + // Once we have starting point, we simple need to go next, next + // of next using given hash map + String to = dataset.get(start); + while (to != null) { + System.out.print(start + "->" + to + ", "); + start = to; + to = dataset.get(to); + } + } + + // Driver function + public static void main(String[] args) { + Map dataSet = new HashMap(); + dataSet.put("Chennai", "Banglore"); + dataSet.put("Bombay", "Delhi"); + dataSet.put("Goa", "Chennai"); + dataSet.put("Delhi", "Goa"); + + printResult(dataSet); + } + +} diff --git a/Heap&Hashing/prob13.class b/Heap&Hashing/prob13.class new file mode 100644 index 0000000000000000000000000000000000000000..68c38a456da4d217136855396ccf9eb987ffa7d1 GIT binary patch literal 875 zcmY*XO-~b16g_V~`d~VMd`v}X0l{KhYAYgTfv_=An}9=7gQ>)XY5ORH(;3oEN!j#&e7%o(_WG{-#0O@`P#*LTBp1~rr2X3*{j4Z$$9;rilnw^bAECr-_y zOuW-=1$&KtY?)!85<2x4o6cbb0Sqz>M^)X>^@@+2&VEIN961vU$eXx@f{CIG zw^86&G;s$@CWbM>ao5B$N+hq>lHtk)ytpv zg}o$MtUJ_J!*$G995J8s| zSiN#LC~nc1LK>EET0}7#Dg8f9+72biqZwb<4CBPJ!%l7m6}DfD5QgwG&B zW^$ONH$8_nWMI?jIpyofW0a8N(9WnZ#xce?EXK&6KK~18a+AQ-b2kskjY{Y_{>`YW ynqAd&yQ;_RYK+?(3#V%z(YKI1LH{Qh7h@TrBG7Xh!xA-GCJ`lSH%>VP*Zu&kf~va! literal 0 HcmV?d00001 diff --git a/Heap&Hashing/prob13.java b/Heap&Hashing/prob13.java new file mode 100644 index 0000000..f9f6d54 --- /dev/null +++ b/Heap&Hashing/prob13.java @@ -0,0 +1,56 @@ + +/** + * Subarrays with distinct elements + * + * Input : arr[] = {1, 2, 3} + * Output : 10 + * {1, 2, 3} is a subarray of length 3 with + * distinct elements. Total length of length + * three = 3. + * {1, 2}, {2, 3} are 2 subarray of length 2 + * with distinct elements. Total length of + * lengths two = 2 + 2 = 4 + * {1}, {2}, {3} are 3 subarrays of length 1 + * with distinct element. Total lengths of + * length one = 1 + 1 + 1 = 3 + * Sum of lengths = 3 + 4 + 3 = 10 + * + * Input : arr[] = {1, 2, 1} + * Output : 7 + * + * Input : arr[] = {1, 2, 3, 4} + * Output : 20 + * + */ + +import java.util.*; + +public class prob13 { + public static int sumoflength(int[] arr, int n) { + Set set = new HashSet<>(); + int j = 0, ans = 0; + for (int i = 0; i < n; i++) { + while (j < n && !set.contains(arr[j])) { + set.add(arr[j]); + j++; + } + + // Calculating and adding all possible length + // subarrays in arr[i..j] + ans += ((j - i) * (j - i + 1)) / 2; + + set.remove(arr[i]); + } + return ans; + + } + + // Driver Code + public static void main(String[] args) { + int[] arr = { 1, 2, 3, 4 }; + int n = arr.length; + + System.out.println(sumoflength(arr, n)); + } + +} diff --git a/Heap&Hashing/prob14.class b/Heap&Hashing/prob14.class new file mode 100644 index 0000000000000000000000000000000000000000..bcc8d4413fdfcf1907d39f07cede849be67c8e26 GIT binary patch literal 1501 zcmaJ>TW=Fb6#mAyU2istV+gb~rlt+laUf1wE&+$o;x@#^iCY;3xx92@Pm)d6v)1l7 zDDV9d?GqA0;+Z}KL{Y>u|Db;b^>)VI5L=1*Fqbp)oo~)}=FGhN=k)=A8(6iF!i0g0 zg$O1r7&xzIpXx4a;DTQHEQ!xCnI?SB!W8m)Z`#CV3!}JVV8%d!A+g{{M=df$b5m;! zv69ym45JlCiq%eQUHA|9x=Sneh9jFReB1LKwZ{<8Jt}Mba82>X&I)gbuvm*blHpA5 zQDvL&@`B6dW}&8hM{X81-l};Wzaf?!%{kQez4f`PGa6}Q3~7e3u2)AnZef`RTSRPQ z7IQYf#8)=1;@TmkOI(&pYzp7Tb=)v8Z{sFzF{JK#o(h!D+bcqCdCg!nfue~88@I7& z;Es*2@r{kUC^4MQu6o%+Sy|zVmXONEIL=UNdf^e_k(BECwrD5@W0$)fQQgo|%Ts+? z!;p%kuHi{V*$D0nO4xX=57c8RPW?n_-xNf5>7?D`4h*Iv)tWxKdtv2)*lK%$5-r;B zIz&0%b9cPL50rgHcOZDHXyIFY$8hR{e%CmUQnbkr8j0>z~Y zbo2uv!wV&zZe|A0pyagmi7wT_fa<<7h_-cz^Czf2F1kOvVd4xd>C60{Ve;r|9J%Z5 zh_KjtDwcRddH$Y(3f*SK^L9FIs^qei!Y{cz2n0#{wLgfEqgOY}TsB=1O!gd$eUXJq z`c?)UAMCZo3Gn_WaaaMzDN5XRYmO2{11k&{kLf!pHiq;6kHZCe^C|iXfGFq*Ax-@$ zvNAL>8sqtwU@vGwPlEbHcQFb}zXY0V=%3^oqw(<{h}2&qT8ZAC$R9ifpUzLryh3ar z@!xRggOPX(V;^Sh=fzC^Anrax`gbG=`I<=twuX>lmha943XCqJJ(!vsolDPs~dg!adqw!wBl6d5bWT!rvt!XUXd{;(x<3 z5Mh5|fxXAr$a`W+;v;+<%KVW;MhH2VO1`n`(Rj5UqZX%@pk|oWx=Agijg*m~&P-G* t)2}dcl)Vwk6o~RNk map = new HashMap(); + for (int i = 0; i < arr.length; i++) { + if (map.containsKey(arr[i])) { + int count = map.get(arr[i]) + 1; + if (count > arr.length / 2) { + System.out.println("Majority found :- " + arr[i]); + return; + } else + map.put(arr[i], count); + } else { + map.put(arr[i], 1); + + } + } + System.out.println(" No Majority element"); + + } + + // method 2:(Using Moore’s Voting Algorithm): + void printMajority(int a[], int size) { + /* Find the candidate for Majority */ + int cand = findCandidate(a, size); + + /* Print the candidate if it is Majority */ + if (isMajority(a, size, cand)) + System.out.println(" " + cand + " "); + else + System.out.println("No Majority Element"); + } + + int findCandidate(int a[], int size) { + int maj_index = 0; + int count = 1; + for (int i = 1; i < size; i++) { + if (a[maj_index] == a[i]) + count++; + else + count--; + if (count == 0) { + maj_index = i; + count = 1; + } + } + return a[maj_index]; + + } + + /* + * Function to check if the candidate occurs more + * than n/2 times + */ + boolean isMajority(int a[], int size, int cand) { + int i, count = 0; + for (i = 0; i < size; i++) { + if (a[i] == cand) + count++; + } + if (count > size / 2) + return true; + else + return false; + } + + public static void main(String[] args) { + int a[] = new int[] { 2, 2, 2, 2, 5, 5, 2, 3, 3 }; + findMajority(a); + } +} diff --git a/Heap&Hashing/prob15.java b/Heap&Hashing/prob15.java new file mode 100644 index 0000000..ab3e71a --- /dev/null +++ b/Heap&Hashing/prob15.java @@ -0,0 +1,32 @@ +/** + * Given an array arr[] of size ‘n’ and a positive integer k. Consider series of + * natural numbers and remove arr[0], arr[1], arr[2], …, arr[n-1] from it. Now + * the task is to find k-th smallest number in the remaining set of natural + * numbers. + * + * + */ + +public class prob15 { + + // smallest element. + static int ksmallest(int arr[], + int n, int k) { + for (int i = 0; i < n; i++) { + if (arr[i] <= k) + k++; + else + break; + } + return k; + } + + // Driver Code + public static void main(String args[]) { + int k = 4; + int arr[] = { 1, 3 }; + int n = arr.length; + System.out.println(ksmallest(arr, n, k)); + } + +} diff --git a/Heap&Hashing/prob16.class b/Heap&Hashing/prob16.class new file mode 100644 index 0000000000000000000000000000000000000000..7aa4200a3ec161c7f6960bf89979a18bfefb8b8e GIT binary patch literal 1315 zcmZuxO>fg!6g@9-{2a%$ZmA1t8la^>k`753ATUh{ALT2wU_@prMHOP4#1u1$T^t8d zX=c|yGNX~$&ai-jP{o?Rz={IAhtCS7wN2vI`8t ztkX0Z`sXd%ywz>jP4`!$-XhP?eamjn&9~a&ObCB8-=cC zwF>iA$15@Hsd`4^kDJDFkk9cmL%eD&*@oA332t)NyqOTEW!OuFitU+8rdui#n9w#X zJ1Eu@Q1x8PUMl&l<*L(l8|GEZXPQ`co%)Gl-lwFXA1cR51*dSDqo|N*XE}aRFpUz& zjDmA0D>#n}92XT_!Ys#S1y^vD-q?(YaWN9_b3RJu3y2c8vBpS~0ihlnNDL}1Ap-MhdPlf7A$1~f6 z<#efz7D{3{h1;ZuN2-`cn>5=SQ2O4@z?c1?7K!O|AnC+Tkiam$V@JXje@y_B z#$p@fjdKh$`p5($;1g2V7gX9$$VrTl9KKrjNCJUuN#(EQT2z(wnxHCrEvEMCHBlYV zYg`@FYmz#o*HlqW>hr34j+d#o$@J(N63?M*Ydjc0jnMO!LY_8anw~*Ad_mdKui(@u AIRF3v literal 0 HcmV?d00001 diff --git a/Heap&Hashing/prob16.java b/Heap&Hashing/prob16.java new file mode 100644 index 0000000..5b84f0d --- /dev/null +++ b/Heap&Hashing/prob16.java @@ -0,0 +1,31 @@ +import java.util.*; +import java.util.stream.Collectors; + +public class prob16 { + public static List findKClosestElements(int[] nums, int k, int target) { + int left = 0; + int right = nums.length - 1; + + while (right - left >= k) { + if (Math.abs(nums[left] - target) > Math.abs(nums[right] - target)) { + left++; + } else { + right--; + } + } + int arr[] = Arrays.copyOfRange(nums, left, right + 1); + for (int i : arr) { + System.out.println(i); + } + + return Arrays.stream(nums, left, right + 1).boxed() + .collect(Collectors.toList()); + } + + public static void main(String[] args) { + int[] nums = { 10, 12, 15, 17, 18, 20, 25 }; + int target = 16, k = 4; + + System.out.println(findKClosestElements(nums, k, target)); + } +} diff --git a/Heap&Hashing/prob17.class b/Heap&Hashing/prob17.class new file mode 100644 index 0000000000000000000000000000000000000000..84d54fce49d307174047ee8ae341862972641770 GIT binary patch literal 1445 zcmaJ=O>^5s7=G54w2q?Sq*Mv{aOy(Z+D=GlOC6}w05OCbVhlKwj>)C6y-k(KT9332 zlMY9I1j7Y}OE0;=A?*|=eK%$|jPS z<4Bo^Va`MX^U>~7w4|fuGRLdY^=l(oz!eiO;pzp7%$Zok636Qt%M8Yv>$_^5A)d+Z zFla^D6b#8N*B763T6Ga@J9Uq4tcLV`(NLeuwg@RKvs)@4)etmU0^0Y9H35Ka|R7bhq z%BO)V16Lh=))5_H;SF53a053jyop;D@>pe-vZC zK=j9>2V&D{C>b1ad`u15lJcO_rui!o_MqrFVHnNdH-qx_bM!iU*YTU42p4*Rg@G>g zfehRX1#Ta;#S7dAhxp$3ulJ)Spg!`6Sm%(P}3%Xz+J^QX{Gpx^u2V2{uKSUQ2BeTSQ5`L9TvU?i^% z?Ddqb+4}wa>q}kR4}E<0d+M0#$GQkNhy-9k!x*6*$0$)s(w`|pJWZHyU=nL&H|X>c zX0U@<)QRps=J6#i;SotPNg3v#8;LUt;v7?qBSzm8jWYg1YL)oELh(KRWvUgYh%Eob zti^eyrWuu*u2*WtxKY_!JiYT1%*DB<7=1>taDuUOIWJHsaFyU(ql8&xkfT&HbQdF7 XcgdPmWRrk?Nae24IYH+Pec68i6oXR3 literal 0 HcmV?d00001 diff --git a/Heap&Hashing/prob17.java b/Heap&Hashing/prob17.java new file mode 100644 index 0000000..f19002d --- /dev/null +++ b/Heap&Hashing/prob17.java @@ -0,0 +1,43 @@ +import java.util.PriorityQueue; + +/** + * Connect n ropes with minimum cost + * + * + * + */ + +public class prob17 { + public static int connectRopes(int len[], int n) { + if (n == 0) { + return -1; + } + + if (n == 1) { + return len[0]; + } + PriorityQueue minHeap = new PriorityQueue<>(); + int cost = 0; + for (int i : len) { + minHeap.add(i); + } + + while (minHeap.size() != 1) { + int firstSmall = minHeap.poll(); + int secondSmall = minHeap.poll(); + + cost += (firstSmall + secondSmall); + minHeap.add(firstSmall + secondSmall); + } + + return cost; + + } + + public static void main(String args[]) { + int len[] = { 4, 3, 2, 6 }; + int size = len.length; + + System.out.println("Total cost for connecting ropes is " + connectRopes(len, size)); + } +} diff --git a/Heap&Hashing/prob3.java b/Heap&Hashing/prob3.java index f83d1bb..2cbe949 100644 --- a/Heap&Hashing/prob3.java +++ b/Heap&Hashing/prob3.java @@ -33,6 +33,7 @@ public int kthLargest(int arr[], int n, int k) { heap1.remove(); } } + return heap1.peek(); } diff --git a/Heap&Hashing/prob6.java b/Heap&Hashing/prob6.java index 3c50eb5..e088b04 100644 --- a/Heap&Hashing/prob6.java +++ b/Heap&Hashing/prob6.java @@ -41,7 +41,6 @@ static void printMax(int arr[], int n, int k) { } q.addLast(i); } - for (; i < n; ++i) { // The element at the front of the // queue is the largest element of diff --git a/Heap&Hashing/prob9.class b/Heap&Hashing/prob9.class new file mode 100644 index 0000000000000000000000000000000000000000..49aa3f68938d99e277a63f93e6e42062ba56f736 GIT binary patch literal 821 zcmY*WO-~b16g{u=@!Da4N-Zk10t(m;+9qfqh>#eKNt0@gC7OoSw2Wl1ooUKc!=9ag z!r+398(k#xs;02bj`NMbaF3%F?E62>e@ zj9bVdud>S$6B3gG<{dxqqg4T|P<$$&-wQW9f#Iqjc#ry>rq^3@n{B>iT46tkp83H> z`0BpD9r-~k;&frXQYlsh2J4aAdhyWhp27!X_!&?tU?pbgxPBloT3D}cxi8&v+YL6$ z^{D3uo6D+i)x&(w~P|_Ckte)S)sFN=_S-tcI<~~xpy4e5ygAJCu z39+lO{FZyi$wa){Avq{0!HcFajS*fnhgnQ8pFt6Ga8P3J7H(je$PCP%(1kdL6eGqF zl1G%0R7XD*wnk67TB&5^Hr`_F0}@W&IXr-tJAnQXMl9mH@^_+PBp#S2|4ocx9+PBK zTqz`ukq}3`ONzoWrwmoXHMXy(9vM#)EWk(Y1SH2)*4CHX%Y literal 0 HcmV?d00001 diff --git a/Heap&Hashing/prob9.java b/Heap&Hashing/prob9.java new file mode 100644 index 0000000..c2f3420 --- /dev/null +++ b/Heap&Hashing/prob9.java @@ -0,0 +1,87 @@ + +/** + * Count distinct elements in every window of size k + * + * Given an array of size n and an integer k, return the count of distinct + * numbers in all windows of size k. + * + * Input: arr[] = {1, 2, 1, 3, 4, 2, 3}; + * k = 4 + * Output: 3 4 4 3 + * + * Explanation: + * First window is {1, 2, 1, 3}, count of distinct numbers is 3 + * Second window is {2, 1, 3, 4} count of distinct numbers is 4 + * Third window is {1, 3, 4, 2} count of distinct numbers is 4 + * Fourth window is {3, 4, 2, 3} count of distinct numbers is 3 + * + * Input: arr[] = {1, 2, 4, 4}; + * k = 2 + * Output: 2 2 1 + * + * Explanation: + * First window is {1, 2}, count of distinct numbers is 2 + * First window is {2, 4}, count of distinct numbers is 2 + * First window is {4, 4}, count of distinct numbers is 1 + * + */ +import java.util.*; + +public class prob9 { + // method 1 : + static int countWindowDistinct(int win[], int k) { + int dist_count = 0; + for (int i = 0; i < k; i++) { + int j; + for (j = 0; j < i; j++) { + if (win[i] == win[j]) { + break; + } + } + if (j == i) { + dist_count++; + } + } + return dist_count; + } + + static void countDistinct(int arr[], int n, int k) { + // Traverse through every window + for (int i = 0; i <= n - k; i++) + System.out.println(countWindowDistinct(Arrays.copyOfRange(arr, i, arr.length), k)); + } + + static void countDistinctUsingHashing(int arr[], int k) { + HashMap hM = new HashMap(); + for (int i = 0; i < k; i++) + hM.put(arr[i], hM.getOrDefault(arr[i], 0) + 1); + + System.out.println(hM.size()); + for (int i = k; i < arr.length; i++) { + + // Remove first element of previous window + // If there was only one occurrence + if (hM.get(arr[i - k]) == 1) { + hM.remove(arr[i - k]); + } + + else // reduce count of the removed element + hM.put(arr[i - k], hM.get(arr[i - k]) - 1); + + // Add new element of current window + // If this element appears first time, + // set its count as 1, + hM.put(arr[i], hM.getOrDefault(arr[i], 0) + 1); + + // Print count of current window + System.out.println(hM.size()); + } + } + + public static void main(String args[]) { + int arr[] = { 1, 2, 1, 3, 4, 2, 3 }, k = 4; + + countDistinct(arr, arr.length, k); + } + +} diff --git a/Linkedlist/SigleLinkedlist/CloneList$Node.class b/Linkedlist/SigleLinkedlist/CloneList$Node.class new file mode 100644 index 0000000000000000000000000000000000000000..58d22b4c2ed8951b2cf07638e1929a5d83737307 GIT binary patch literal 403 zcmYk2%}T>S6ot?9Cu!=~*4p}46&HeS7IvwixCw}XP!~!U?xxKkDd_}~RD3NLMR4H* z_)y|W7RAM!?V`BmNT6` zt65BE^C?-SbA2Bb53P;xa-rV1Lt~<|{2|G58^;nYoJiPcNNht&IFSEG${n~>F*%Nv zc^yB_7JAP0osCwYIvh=L#?Q6*BdR>~F;Un`QcVh;7TRQo)ir9UkUjSk!X2zpab5AU oMs;VHYlM=<;2Kb+2R}TV#{oI{IYe4_f9$eET~ixn6n@^Yu$vG*N(&XWZKy#*5}Km5Drsp;DkV0dou*RTs+}dg!op@ZlU=Gf ze*6Jvyz!!5cN{LfP&=(S)p7KOalG>nIOG4Y;`8nX0;LMO?|IMnInOzp-~V~|Gk{l6 zj-dyMD28w}3IornBiTn)DuxlH6`RqKjggKTI2J=Uat4koI;P`A9WM!JGw!?;h!-74 zHVU@sdD0W;IAuAOKOxYT8kwb0Au#GGS&p1psm;m8Rddd!TYJ4>IljRDRHLj*DjR{Ld#xXLXU>{wIRXQzo24c5wwbd{XCYVdnQtKo9;>)3 zjjEioR2|*h*^en>fzBD}`DLj}_2THmejO*`co`?-#O>8MUceAejtP;c>qROi0%NpT#SE%R@5wP6cWd%1ukY+7Uh~`b7y^10S)-auU zmma;3BN@Yaye@FyJZ%%F6C#_q5}2yHz`>fiEDNqvHT`RrzsQ^Cn~u*F7)TY1BYUCe ztb@vT7bBntn_zQd{i(fP!4f(012&_jiX*c+rWD95JlVp*a&EiJvN_|hrYW=PyNy*H z7ujOTb(dG_0(W*MXgY-hoMvaX^pc@ves3K+B)c51uGZxf%y+I{IHmkfNSYxErfpX& zU*>g`1cvuC^rYGZ4*$O$Kk9CN-Re(+P#eti0J%e?g0wxo4)Gl?M4V?wAROYS&IROM znZAuSL`a9zrOXC~?je%7k2by<$wRaQ-=l-9URvAyONELAp$3!&IdaDtb_~zr1d=$3 zrznjg@;4$n43&vX9cB_sEK)grl`e@gb0t;Oa^^=E*Hy}OL?1v`vMgzq>HZ8#8dIVT z98rX?wt+51$gPEf2hfy`4}Jbf&!l-9*9Nun=my3|M?)1u4pK&D1Kk1Tbqz*vrBa#A z1kAX$w)tE3+wD$o5G?SwK;teNm_QfKu-mij_8fme3&`LCahPWBMM~blMgCvGWxRt5 zB;Ld#uEEAzcpumC8E)VU+{BlJ{Vr|=XjRbp2pZAilN7gjZgM1Tp@3(ABxxk}2(eIF zCD~MHhV1saWx9_ec!os=6BhlnY-0<*Dx@{STnaF6Zvn0p9W9nnD2cvH(i9p^VH5Et z_Lnext->random= original->random->next; /*TRAVERSE + * TWO NODES* + * + * + * This works because original->next is nothing but a copy of the original and + * Original->random->next is nothing but a copy of the random. + * + * Now restore the original and copy linked lists in this fashion in a single + * loop. + * + * + * original->next = original->next->next; + * copy->next = copy->next->next; + * + * + */ + +public class CloneList { + // Structure of linked list Node + static class Node { + int data; + Node next, random; + + Node(int x) { + data = x; + next = random = null; + } + } + + // Utility function to print the list. + static void print(Node start) { + Node ptr = start; + while (ptr != null) { + System.out.println("Data = " + ptr.data + + ", Random = " + + ptr.random.data); + ptr = ptr.next; + } + } + + static Node clone(Node start) { + Node curr = start, temp = null; + // insert additional node after + // every node of original list + + while (curr != null) { + temp = curr.next; + curr.next = new Node(curr.data); + curr.next.next = temp; + curr = temp; + } + curr = start; + + // adjust the random pointers of the + // newly added nodes + while(curr != null){ + if(curr.next != null){ + curr.next.random =(curr.random != null) + ? curr.random.next + : curr.random; + } + + // move to the next newly added node by + // skipping an original node + curr = curr.next.next; + } + + Node original = start, copy = start.next; + // save the start of copied linked list + temp = copy; + + while (original != null) { + original.next =original.next.next; + copy.next = (copy.next != null) ? copy.next.next + : copy.next; + original = original.next; + copy = copy.next; + + } + return temp; + + } + // Driver code + public static void main(String[] args) + { + Node start = new Node(1); + start.next = new Node(2); + start.next.next = new Node(3); + start.next.next.next = new Node(4); + start.next.next.next.next = new Node(5); + + // 1's random points to 3 + start.random = start.next.next; + + // 2's random points to 1 + start.next.random = start; + + // 3's and 4's random points to 5 + start.next.next.random = start.next.next.next.next; + start.next.next.next.random + = start.next.next.next.next; + + // 5's random points to 2 + start.next.next.next.next.random = start.next; + + System.out.println("Original list : "); + print(start); + + System.out.println("Cloned list : "); + Node cloned_list = clone(start); + print(cloned_list); + } +} diff --git a/Linkedlist/SigleLinkedlist/FlatternList$Node.class b/Linkedlist/SigleLinkedlist/FlatternList$Node.class new file mode 100644 index 0000000000000000000000000000000000000000..bea972a61f55fe69195d7914b484dd0c1e597936 GIT binary patch literal 481 zcmZ8d%T59@6g}lJ17m>!e1M`nWC3F$?p$b03<;5h;6lTGfCh#PGs(2*cex-YF8lyL z%6K~~aM5$x-h0lu?a%MmH-KBTvM^A!VB%Eo&NS3CoSV2XQD;caUF9;cAwxRy7E47} z<8Uq*_%H}W)c0K}g=8p?2EMD5h=P$PRa^JmX?ge_Fc@m-$@UFHey@ufjC(Ke)B{7Q zvtJr^CnWF3QH7Bgi1B7U7166Z^(owX2{+M93_N`(?j~Qa+&3CHGZs=kg;JSla1>y3 z6w&0!Aj@GP$B{?wpEMqt!PX8v-whVM=jlq!=*fIHfg#!HPSBulGU*pnw8)hZ+BjzN z25ejB(wWgJqC{M#-6Il65?7t8EtvC(gj3rh>98$Q8qy!J3l%oT8AivkR)9{_)DBUvB- literal 0 HcmV?d00001 diff --git a/Linkedlist/SigleLinkedlist/FlatternList.class b/Linkedlist/SigleLinkedlist/FlatternList.class new file mode 100644 index 0000000000000000000000000000000000000000..c5a50110f1e3e0a6c75e04e83108345a41299259 GIT binary patch literal 2113 zcmah}OK%%h6#lMbdtztua+h$0>mf&~&13pU*b)HqTru>^@d|A9Zit^&S0;}Dy;MAqCnbDrP%&bj{WuLnN^ zn88XEF~lQKFd>gb6kX7yl$26R!DN&lQxSeV8^Lp!jxp>~l#!R^@q&UErDI$kX?e^l zm=g%*?V=%|W-ZI8E|he~F&t_)4ZSGPm&=rN*EOnE&UD;S>6#V@&zhF$UJ+=EPu!;O zf|sE?XIe&nr@UrVm-V$0bB4-Bb%XD8yhWN8s)-glfzE=fuWv8um3mg?9S@Qv5O0;Y zb&_CZ$JrE^Xcdud9TKTjP0N*iv&FJ*vfx1c&D@rLN1rO`*2Yx9rNc&AQV=cJJJod~ zW6HLB8#$Yl{sJ9&!*Q1kNsgo9G|s5Ff_W7$VL-)`7*cUnO2c^SKk**tGUA$wehesB zQ1LPr1$wU8w(Gc6y|QGun|9IZ4kOc!S5#a_R>7+(ZXl;(31>LmMno#k;b|4mNJGz2 zH#gU|jCI*+QFjSgWTj}o%dSIJb7Pa1STlL)tn9oYLt)o(jWV~w-l2ED&y;CT-I6?# zEJH7I@A9}Q5D@1CPM7sp3Mtzn(n2f&e+SOeJZ*bLfw!OVm5%{(-c|FJ{{<>}z zONKM*d!~z^ED~4k5FolDFR-RaYQI5SZoq1E)dlv7Mj5X zW}#sYmwB1yc#Y1|s{_GsXy_5T6#gYbUaLB)6|^xOFsA*2D9eX@SQ1I7hA=B8G+z$p zw4>Ss2r+1pc{AulmUVAngm+8U3L?-UIpM9U7n!NI-uDp7YGUXB?fI0(9#eiwpR<_9 z&TT}oif+7xUcAjDyp{DNYs4v$o=@CIBuBV|KY54)4~POasFJ+gy}$pUx`s|U44 10 -> 19 -> 28 + * | | | | + * V V V V + * 7 20 22 35 + * | | | + * V V V + * 8 50 40 + * | | + * V V + * 30 45 + * + * + * + * Write a function flatten() to flatten the lists into a single linked list. + * The flattened linked list should also be sorted. For example, for the above + * input list, output list should be + * 5->7->8->10->19->20->22->28->30->35->40->45->50. + */ + +class FlatternList { + Node head; // head of list + + /* Linked list Node */ + class Node { + int data; + Node right, down; + + Node(int data) { + this.data = data; + right = null; + down = null; + } + } + + Node merge(Node a, Node b) { + // if first linked list is empty then second + // is the answer + if (a == null) + return b; + + // if second linked list is empty then first + // is the result + if (b == null) + return a; + + // compare the data members of the two linked lists + // and put the larger one in the result + Node result; + + if (a.data < b.data) { + result = a; + result.down = merge(a.down, b); + } + + else { + result = b; + result.down = merge(a, b.down); + } + + result.right = null; + return result; + } + + Node flatten(Node root) { + if (root == null || root.right == null) { + return root; + } + + root.right = flatten(root.right); + + root = merge(root, root.right); + + return root; + } + + /* + * Utility function to insert a node at beginning of the + * linked list + */ + Node push(Node head_ref, int data) { + /* + * 1 & 2: Allocate the Node & + * Put in the data + */ + Node new_node = new Node(data); + + /* 3. Make next of new Node as head */ + new_node.down = head_ref; + + /* 4. Move the head to point to new Node */ + head_ref = new_node; + + /* 5. return to link it back */ + return head_ref; + } + + void printList() { + Node temp = head; + while (temp != null) { + System.out.print(temp.data + " "); + temp = temp.down; + } + System.out.println(); + } + + /* Driver program to test above functions */ + public static void main(String args[]) { + FlatternList L = new FlatternList(); + + /* + * Let us create the following linked list + * 5 -> 10 -> 19 -> 28 + * | | | | + * V V V V + * 7 20 22 35 + * | | | + * V V V + * 8 50 40 + * | | + * V V + * 30 45 + */ + + L.head = L.push(L.head, 30); + L.head = L.push(L.head, 8); + L.head = L.push(L.head, 7); + L.head = L.push(L.head, 5); + + L.head.right = L.push(L.head.right, 20); + L.head.right = L.push(L.head.right, 10); + + L.head.right.right = L.push(L.head.right.right, 50); + L.head.right.right = L.push(L.head.right.right, 22); + L.head.right.right = L.push(L.head.right.right, 19); + + L.head.right.right.right = L.push(L.head.right.right.right, 45); + L.head.right.right.right = L.push(L.head.right.right.right, 40); + L.head.right.right.right = L.push(L.head.right.right.right, 35); + L.head.right.right.right = L.push(L.head.right.right.right, 20); + + // flatten the list + L.head = L.flatten(L.head); + + L.printList(); + } +} \ No newline at end of file diff --git a/Linkedlist/SigleLinkedlist/index.txt b/Linkedlist/SigleLinkedlist/index.txt index da33f16..542511a 100644 --- a/Linkedlist/SigleLinkedlist/index.txt +++ b/Linkedlist/SigleLinkedlist/index.txt @@ -940,7 +940,7 @@ Delete nodes which have a greater value on right side return head_ref; } - // Function to merge two sorted doubly linked lists + 30 // Function to merge two sorted doubly linked lists static Node merge(Node first, Node second) { // If first linked list is empty if (first == null) @@ -1002,3 +1002,113 @@ Delete nodes which have a greater value on right side } +31.clone linked list +// Java program to clone a linked list with next +// and arbit pointers in O(n) time +class GfG { + + // Structure of linked list Node + static class Node { + int data; + Node next, random; + Node(int x) + { + data = x; + next = random = null; + } + } + + // Utility function to print the list. + static void print(Node start) + { + Node ptr = start; + while (ptr != null) { + System.out.println("Data = " + ptr.data + + ", Random = " + + ptr.random.data); + ptr = ptr.next; + } + } + + // This function clones a given + // linked list in O(1) space + static Node clone(Node start) + { + Node curr = start, temp = null; + + // insert additional node after + // every node of original list + while (curr != null) { + temp = curr.next; + + // Inserting node + curr.next = new Node(curr.data); + curr.next.next = temp; + curr = temp; + } + curr = start; + + // adjust the random pointers of the + // newly added nodes + while (curr != null) { + if (curr.next != null) + curr.next.random = (curr.random != null) + ? curr.random.next + : curr.random; + + // move to the next newly added node by + // skipping an original node + curr = curr.next.next; + } + + Node original = start, copy = start.next; + + // save the start of copied linked list + temp = copy; + + // now separate the original list and copied list + while (original != null) { + original.next =original.next.next; + + copy.next = (copy.next != null) ? copy.next.next + : copy.next; + original = original.next; + copy = copy.next; + } + return temp; + } + + // Driver code + public static void main(String[] args) + { + Node start = new Node(1); + start.next = new Node(2); + start.next.next = new Node(3); + start.next.next.next = new Node(4); + start.next.next.next.next = new Node(5); + + // 1's random points to 3 + start.random = start.next.next; + + // 2's random points to 1 + start.next.random = start; + + // 3's and 4's random points to 5 + start.next.next.random = start.next.next.next.next; + start.next.next.next.random + = start.next.next.next.next; + + // 5's random points to 2 + start.next.next.next.next.random = start.next; + + System.out.println("Original list : "); + print(start); + + System.out.println("Cloned list : "); + Node cloned_list = clone(start); + print(cloned_list); + } +} + + + diff --git a/Searching/BinarySearch.java b/Searching&sorting/BinarySearch.java similarity index 100% rename from Searching/BinarySearch.java rename to Searching&sorting/BinarySearch.java diff --git a/Searching/LinearSearch.java b/Searching&sorting/LinearSearch.java similarity index 100% rename from Searching/LinearSearch.java rename to Searching&sorting/LinearSearch.java diff --git a/Searching&sorting/Node.class b/Searching&sorting/Node.class new file mode 100644 index 0000000000000000000000000000000000000000..621bc069adf5dbab63bb3363711e96ceb4839fdd GIT binary patch literal 276 zcmW+wO>4qX5S)$Cn3x*t*TsuR&7o2XdT8lI5CqYK;{8P*C8CLhSo~Waq~O6H&>vMg z&%@5no1NLWzkjzofDzgrim17;@ob>(py8k?u(v8#0-2H~`kV_&vw6DJ?<5~_66c>B z^rrna+nBl_n8k^npAM1ERw~+4@s{Z++vrJb9+hL3Mz6z{o%&WjJhXh2;P@!R!$6fO_r U6S2-kCTcV6GFW{?tJEw6|A$T~umAu6 literal 0 HcmV?d00001 diff --git a/Searching&sorting/NodeComparator.class b/Searching&sorting/NodeComparator.class new file mode 100644 index 0000000000000000000000000000000000000000..1204e44b5009cb5b2e2823068dbf15730b352475 GIT binary patch literal 563 zcmZXQ%S!@L6vn?h4=1OY)O=*7&?fRl)}|JU5JDiBEsXYebdWKfkzuAkC|bG+qM${z z?vIMj9gRpA=W)-R`}@ARU*GQ^04`9{5kn>p8CeZE9V+%TFdP51+E zOu0L5+*lKP7&JF0;%0o{j9ngtf_u8TvYdp0Gi`Jtc^-IvYbo4rGUx*@^oRD9BOGqe zea|{OKM~Rfwh%XPfFk{paBIMT$*?2(KNLf9-6%sQ8m);EX2b)|z`8i3Cyarfgq~NX zASpWO)Rm|*s%rHO?3o&JMOiEZJCw-;WwF|a6kRUXULe&eo}em=-@_wRX(2CYPl^aR zk_3{}r--nNJkls2OH4q4WE#m!VkcJYBO(i9X0`SSxlZv4MZo^skq9URQUnw={R2@u BZAbtB literal 0 HcmV?d00001 diff --git a/Searching&sorting/aindex.txt b/Searching&sorting/aindex.txt new file mode 100644 index 0000000..4e29a4b --- /dev/null +++ b/Searching&sorting/aindex.txt @@ -0,0 +1,16 @@ +1. Find duplicates in O(n) time and O(1) extra space | Set 1 +2.if there are four elements with given sum. +3. * Permute two arrays such that sum of every pair is greater or equal to K +4.Find common elements in three sorted arrays +5.Searching in an array where adjacent differ by at most k +6. Ceiling in a sorted array +7. Find a pair with the given difference +8.Count triplets with sum smaller than a given value +9.Java program to print all subarrays in the array which has sum 0 +10.Check if reversing a sub array make the array sorted(*) +11.Make all array elements equal with minimum cost +12.count inversion +13.minimum page allocation +14.merge sorted array +15.median-of-two-sorted-arrays-of-different-sizes + diff --git a/Searching&sorting/prob1.class b/Searching&sorting/prob1.class new file mode 100644 index 0000000000000000000000000000000000000000..b4bcfa9eaa745b0866a0b80647a5a5132b40f545 GIT binary patch literal 1055 zcmaJkh3oDhi-?h|IZIu=+ttOg?`XEUo33W9z8d4t|=%j2}b~d|1lfL^S zeAO49^+A)y^amLKgs=XD#;>~zNom?h!pz)z&$)BX-TC(C@Cd*?+%ceIG>tKgr!Zk) z5>um8nAMTfF~^X6V7s<@#1JnmzhFpIv5?`7No1iI!rBZC6j_>j!}nU9v2DRGsJ>vSsNRxl!av@NSu5ENXN*&7gZB$e~e8 z6waH3fn}`Fl`PLN)#V*gk#38tm$qutDNvlOh1}}$S+ZqxOL!( zbKt`dqCfHSu(v^r3U{2ktwdSJZHA>Y{?60JaOM9vEFekGJN(7K!e>RRLD3xTjCO71 z3)n|GFkGND86{%`%V31gA@n;Eh||7rroS4Ec-(3vbgQ8ytwvI_8oEhA%1l`eGYn0g z@@6Vw)#49x#iRF_EEaRC#Ut+(Ew8ONG4|o_&rgVr#y=x5fXqh-t^E#Js^ku#0aT5! zKSFJ>NZU%JCV^F|-zB9L+N)&gIjL<>twktF=N_`SNUU*azp= numRay.length * 2) { + System.out.println(i + " "); + } + } + + } + +} diff --git a/Searching&sorting/prob10.java b/Searching&sorting/prob10.java new file mode 100644 index 0000000..74576e9 --- /dev/null +++ b/Searching&sorting/prob10.java @@ -0,0 +1,57 @@ +/** + * Check if reversing a sub array make the array sorted + * + * + */ + +public class prob10 { + static boolean checkReverse(int arr[], int n) { + if (n == 1) { + return true; + } + int i; + for (i = 1; arr[i - 1] < arr[i] && i < n; i++) + ; + if (i == n) { + return true; + } + // Find reversed part + int j = i; + while (j < n && arr[j] < arr[j - 1]) { + if (i > 1 && arr[j] < arr[i - 2]) { + return false; + } + j++; + } + if (j == n) { + return true; + } + // Find last increasing part + int k = j; + // To handle cases like {1,2,3,4,20,9,16,17} + if (arr[k] < arr[i - 1]) { + return false; + } + while (k > 1 && k < n) { + if (arr[k] < arr[k - 1]) { + return false; + } + k++; + } + return true; + + } + + // Driven Program + public static void main(String[] args) { + + int arr[] = { 1, 3, 4, 10, 9, 8 }; + int n = arr.length; + + if (checkReverse(arr, n)) { + System.out.print("Yes"); + } else { + System.out.print("No"); + } + } +} diff --git a/Searching&sorting/prob11.java b/Searching&sorting/prob11.java new file mode 100644 index 0000000..01041e7 --- /dev/null +++ b/Searching&sorting/prob11.java @@ -0,0 +1,60 @@ +/** + * Make all array elements equal with minimum cost + * + * Input : arr[] = [1, 100, 101] + * Output : 100 + * We can change all its values to 100 with minimum cost, + * |1 - 100| + |100 - 100| + |101 - 100| = 100 + * + * Input : arr[] = [4, 6] + * Output : 2 + * We can change all its values to 5 with minimum cost, + * |4 - 5| + |5 - 6| = 2 + * + * + * Alternate Solution + * Think geometrically. Assume that array elements are co-ordinates on x axis. + * The problem reduces to finding another co-ordinate such that the sum of + * distances between this choice and other co-ordinates is minimized. + * Observe that: If number of coordinates are odd then y = middle element. If + * even then y is any number in between middle 2 co-ordinates. Say Input = [a, + * b, c, d]. Output is any number between b and c including both. Hence the cost + * is sum which can be computed easily now that we have chosen y. sum|(y-ai)| + * for all i. + * + * It is really easy to code it. + * + * + */ + +public class prob11 { + // This function assumes that a[] is + // sorted. If a[] is not sorted, we need + // to sort it first. + public static int minCostToMakeElementEqual(int a[], int n) { + int y; + if (n % 2 == 1) { + y = a[n / 2]; + } + + else + y = (a[n / 2] + a[(n - 2) / 2]) / 2; + + // After deciding the final value, + // find the result. + int s = 0; + + for (int i = 0; i < n; i++) + s += Math.abs(a[i] - y); + return s; + + } + + // Driver code + public static void main(String[] args) { + int a[] = { 1, 100, 101 }; + int n = a.length; + + System.out.println(minCostToMakeElementEqual(a, n)); + } +} diff --git a/Searching&sorting/prob12.class b/Searching&sorting/prob12.class new file mode 100644 index 0000000000000000000000000000000000000000..a10d287f7cfc6cf0fef3ba8c3a4385155e00b623 GIT binary patch literal 1261 zcmZ`(O>Y}j6g|)LX5P%yp=sI)b;px_(Z-&DO(JR}(xwWPKyCwu8db8g@x&e?7k_Cw zuE>I&S1kDnp^`Uj009+3`2nn1@E6KYKm~Kgo?;NfvfjJzzI*RG_nd40{O6A+0N%uw z4GW%)HC(h|;!?6)wr~YkZM=eO7LV5z))fi@S`bA7nfRp9JD@pFBqm_OT92U40rqO zG|)@}lTd|I0%vBo^+6ObBGfD*sU>?sr!TNt*x!2?JPyj;pnq7d$5E$$xSe1#Z??KA zSi3$LMXm6i&J5Zx8XRnHm6D_^vRG0mX5nKai&eaw#aWzFcr}aHP*Nyo@j5oMuoFDS zJX2tK@nG%XVc24ebJr;Dbj!O@6dXMw2d%;IsP^%F;vysS)`|&<|46SNJ&MB~=^Tt$ z#F=-}8I(U@8!?*+gWk5l+1Y#lb_=Ls64WIJvQRBPz-4M?QCz;2;H72IW`kT`;>qJK zxaD+g7(lJUo-BG14 z;rNa@HbvqZ8=_R3On*r|ydNui9E)XL$7r^j6>Bp6F0J<8#Aj*!7dI~oOs3BqYe7JT z4Pw@Ij;l*TJZ$mzb{iM*A;oIaGsHD~itG3s>-Yi%JRvm+DIWAGuWbcK2*Gu3P`%Px zE=N8%si{;w@->%g$ITyO!_7DKZbf>&>&U0jnmZn)lFfW-(@Rs*y+FD~nLunAyg};* zhh-b*af|;0w<*)xGejJv=O_z`cOJR)>HB;*!%W}&$!=(}){x8RY7Kqas5J~#Ybdj} z_YL$7ZR13?`TX}V7E`x61N|;8pvsZBOAe~+{T>J7!rudXgVHA-?| arr[j]) + inv_count++; + + return inv_count; + } + + + //method 2 + // Function to count the number of inversions + // during the merge process + private static int mergeAndCount(int[] arr, int l, + int m, int r) { + + // Left subarray + int[] left = Arrays.copyOfRange(arr, l, m + 1); + + // Right subarray + int[] right = Arrays.copyOfRange(arr, m + 1, r + 1); + + int i = 0, j = 0, k = l, swaps = 0; + + while (i < left.length && j < right.length) { + if (left[i] <= right[j]) + arr[k++] = left[i++]; + else { + arr[k++] = right[j++]; + swaps += (m + 1) - (l + i); + } + } + while (i < left.length) + arr[k++] = left[i++]; + while (j < right.length) + arr[k++] = right[j++]; + return swaps; + } + + // Merge sort function + private static int mergeSortAndCount(int[] arr, int l, + int r) { + + // Keeps track of the inversion count at a + // particular node of the recursion tree + int count = 0; + + if (l < r) { + int m = (l + r) / 2; + + // Total inversion count = left subarray count + // + right subarray count + merge count + + // Left subarray count + count += mergeSortAndCount(arr, l, m); + // Right subarray count + count += mergeSortAndCount(arr, m + 1, r); + // Merge count + count += mergeAndCount(arr, l, m, r); + } + + return count; + } + + // Driver code + public static void main(String[] args) { + int[] arr = { 1, 20, 6, 4, 5 }; + + System.out.println( + mergeSortAndCount(arr, 0, arr.length - 1)); + } + +} diff --git a/Searching&sorting/prob13.java b/Searching&sorting/prob13.java new file mode 100644 index 0000000..db3c833 --- /dev/null +++ b/Searching&sorting/prob13.java @@ -0,0 +1,61 @@ +public class prob13 { + // Page allocation problem + // n = number of pages in a different book + // m = number of students + // all the books have to be divided amongs m students consecutively . allocate + // the pages in such a way that maximum pages allocated to + // student is a minimum + + static boolean isPossible(int arr[], int n, int m, int min) { + int studentRequiered = 1, sum = 0; + for (int i = 0; i < n; i++) { + if (arr[i] > min) { + return false; + } + // pages we are giving to current student + if (sum + arr[i] > min) { + studentRequiered++; + // if we want to give min pages to student cant increase it ferther + sum = arr[i]; + if (studentRequiered > m) { + return false; + } + + } else { + + sum += arr[i]; + } + } + return true; + } + + static int allocateMinimumPages(int arr[], int n, int m) { + int sum = 0; + if (n < m) { + return -1; + } + for (int i = 0; i < n; i++) { + sum = sum + arr[i]; + } + + int start = 0, end = sum, ans = Integer.MAX_VALUE; + while (start <= end) { + int mid = (start + end) / 2; + if (isPossible(arr, n, m, mid)) { + ans = Math.min(ans, mid); + end = mid - 1; + } else { + start = mid + 1; + } + } + return ans; + } + + public static void main(String[] args) { + int arr[] = { 12, 34, 67, 90 }; + int n = 4; + int m = 2; + System.out.println(allocateMinimumPages(arr, n, m)); + } + +} diff --git a/Searching&sorting/prob14.class b/Searching&sorting/prob14.class new file mode 100644 index 0000000000000000000000000000000000000000..392ce12f8c495c0e1e2b2ed60edc43d56f108694 GIT binary patch literal 1024 zcmZ`%-%rzE6g}VCty}5b1co>^*g$2VZXz&5kc4P3Ghj(((1jPfQAu$>NY|P0&R>EL zJQ^`UVhj&H`hWOufamKVXpCF(-P`k>d+)iY{dxB76u=zjbwrVlz`(FPMs#G5)tQY( zFos)U+}3di;}XuvY$A+F4RvfzYDUbi5@2B{#7_^l59$7Kp7n zP5Wi1QMKJyR<%wf*s$Gg8FQtQBu2}gReQf??Oxog4a;c?4CFRfcdQRqp>8#|3uVuB zn%fJKA6~50FDB{bR>!T`D~{~jv+K61Q!{y4WZ*h_4O~OaKpZg*_YLGxFp$82h6e_w zK*g!$cb@HL)~JWgGy00-w!O@<>sot{Ga9B1%wX0)5pxC}VV293?OLn3bxFx^>F!X0 z_?1?(x?|V8OQ_>H^@88CO;g$}mp8%OroZ|hMdiJ=XE$hGt3yJfySmdVtaERV+uK%S zL7>l{@;A(OyOPAJ+D0pJ%8GvWQkQm())z4Kcn}o+wL6b*reR66!}RrH2kMe}q6Pe*`6+ zKR{$ZAP&!e`A@~547^RKdD9Pxpt-Mzef9kC{0D&(sATYz!vp^CqOV+s{G9ulXSu;R z)#s^up30Xg=NWIFQ``#-VjVZJfh2CQgAU~k5g|l+l=XwW>56~L-g3_wjy&bS(-Tlx zs8>5in9&y!IfgE=o=c3fBz9#>(l;QD9t=~%2>%%>%VHX%v?@t$-Dz)VmHaKnL*Mm^ zqM8*oY*vEth*=56b+e+yV`e2B?>E07ph-rMjF4oI7K%rSD_2u>YL~BM3>y0nF%Ka1 E8ya4}Jpcdz literal 0 HcmV?d00001 diff --git a/Searching&sorting/prob14.java b/Searching&sorting/prob14.java new file mode 100644 index 0000000..05d42e2 --- /dev/null +++ b/Searching&sorting/prob14.java @@ -0,0 +1,66 @@ + +/** + * Merge two sorted arrays with O(1) extra space + * Input: ar1[] = {10}; + ar2[] = {2, 3}; +Output: ar1[] = {2} + ar2[] = {3, 10} + +Input: ar1[] = {1, 5, 9, 10, 15, 20}; + ar2[] = {2, 3, 8, 13}; +Output: ar1[] = {1, 2, 3, 5, 8, 9} + ar2[] = {10, 13, 15, 20} + + * + */ +import java.util.*; + +public class prob14 { + static int arr1[] = new int[] { 1, 5, 9, 10, 15, 20 }; + static int arr2[] = new int[] { 2, 3, 8, 13 }; + + static void merge(int m, int n) { + int i = 0, j = 0, k = m - 1; + + while (i <= k && j < n) { + if (arr1[i] < arr2[j]) { + i++; + } else { + int temp = arr2[j]; + arr2[j] = arr1[k]; + arr1[k] = temp; + j++; + k--; + } + } + + Arrays.sort(arr1); + Arrays.sort(arr2); + } + + // method 2: + + static void merge2(int n, int m) { + int i = 0; + int temp = 0; + + while (arr1[n - 1] > arr2[0]) { + if (arr1[i] > arr2[0]) { + temp = arr1[i]; + arr1[i] = arr2[0]; + arr2[0] = temp; + Arrays.sort(arr2); + } + i++; + } + } + + public static void main(String[] args) { + merge(arr1.length, arr2.length); + System.out.print("After Merging \nFirst Array: "); + System.out.println(Arrays.toString(arr1)); + System.out.print("Second Array: "); + System.out.println(Arrays.toString(arr2)); + } + +} diff --git a/Searching&sorting/prob15.java b/Searching&sorting/prob15.java new file mode 100644 index 0000000..c1db96f --- /dev/null +++ b/Searching&sorting/prob15.java @@ -0,0 +1,49 @@ + +/** + * Simple Mathematical Approach + * + * + * + * + */ +import java.io.*; +import java.util.Arrays; + +public class prob15 { + public static int median(int[] arr) { + int n = arr.length; + + if (n % 2 == 0) { + int z = n / 2; + int e = arr[z]; + int q = arr[z - 1]; + int ans = (e + q) / 2; + return ans; + + } else { + int z = Math.round(n / 2); + return arr[z]; + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + int[] arr1 = { -5, 3, 6, 12, 15 }; + int[] arr2 = { -12, -10, -6, -3, 4, 10 }; + + int i = arr1.length; + int j = arr2.length; + + int[] arr3 = new int[i + j]; + + // Merge two array into one array + System.arraycopy(arr1, 0, arr3, 0, i); + System.arraycopy(arr2, 0, arr3, i, j); + + // Sort the merged array + Arrays.sort(arr3); + + // calling the method + System.out.print("Median = " + Solution(arr3)); + } +} diff --git a/Searching&sorting/prob16.class b/Searching&sorting/prob16.class new file mode 100644 index 0000000000000000000000000000000000000000..d492b9f5a1e2fdeeee2250fcb0de5de847437512 GIT binary patch literal 2328 zcmcIm+jA3D82_C#yC)5c#6pp6kxMBwDJkKi2q}UPK}yqdNo^?wVVf*v+hjMBY#2H| zIpg@|i!WYg^uZTid_V^a1Eb?p9~>Y2FZ6Hl!TLM9iwT!ud~qf@=ewQn^83Dg?XQ17 z`We7m@RHbw-4c6x$Yzs>VMJnI5*l)f*{_ZR>Nwa<*`aQ{fj1R(xCa79lgMKfME^$KQ9RdBA<2wFvfv$9BS|DEVDz?CeqT||=t=hcZn6l=plq73*W5FITI!#|7 zm7Xh3(r|Pv6W#*rOTJZJny~7Dy~Ig@?s~&<{qRM1Iy4Mo)GWsp*i0vj)@>_SwcLeV z$*1wcXl7dCl)%QSRhzF^gYBS$`vReO2F~C;<>V|e zQKc$+%)mK}8z^GJz$DHaxPXfimkg9JW#D~G^Yu&umkrF~io~3OtGH%h3rquB@w$Nz zR8o4FCv#|*e|~<^E)!W90ZRy8fKC$EaYJAz-2q(qa`bsgW=wV4qR+Bdt6L2gy(OIq z?E*v!f!OlB#;AZ9`FvIrG%P))t}d%m5$JtE@XQrPahj)Vb$>aSB=YgPSFH+cdJ;0| za+EB!u6>8)>QBa}1B%je)3w$e#8tpaqlrOs)S;C~FP$Rac^7z=mUB zCk7-IRo|Bc2HJrf_qMlW=Ze8NbJDDvR+)ekrFFG7C&7C4qUSBO>H@}?>)MS%)oM0v zrv6(e;E}&@X3tt~rD`_^!-t(C5arrY@ly|{mg{z>`F~f2Az%Ks6X?iu!KzkEj&HMZ zgU^8zCL6Zx%oBLN`2VYpK$`17DVoohRUpCLwfnguUepnRZ7;XO4*o(na;1a28fs;6 zU2i7!I&Yz*!w(?7C&Ag~sRzP7B-BbFO;Zs^7bJBbJw|Ny5g9x{e4_s+Xp@hj&2~M2 zo{yXHyw-JC@74Rig*n`-A6$izRrd-n?j!2nm^E>^k+84O`R(l|=` z1V*@G_u(uK;5-iDGLCS$9mP!?hl`WAg91LJMISxwguX@>Qlei-#CS<){1Bnuzn~>@ zF?6f_8Y03S9Sd;UI=qU$AFyutK8#091}k`lbaMRe+Mf#3Fxei&Nssd^vK15PXF4iq zocccc-G=QE(nFLbsQE@7Q}9kGc;ke3GTSv$8d01^j!=y-h+_4SRiq5skYyuEW?Tsp zZJi?XT2?c)lBp?Os^eiQc&TS~Q!kl%ppBkp`yXOMUYc?h2~$2qilwgL)pli|i^hUW6Ut38a#09Y)O { + public int compare(Node k1, Node k2) { + if (k1.data > k2.data) { + return 1; + } else if (k1.data < k2.data) { + return -1; + } + return 0; + } +} + +class prob16 { + + static Node mergeKList(Node[] arr, int K) { + // PriorityQueue queue = new PriorityQueue<>(new NodeComparator()); + PriorityQueue queue = new PriorityQueue((p, q) -> { + return p.data - q.data; + }); + Node at[] = new Node[K]; + Node head = new Node(0); + Node last = head; + // Push the head nodes of all + // the k lists in 'queue' + for (int i = 0; i < K; i++) { + if (arr[i] != null) { + queue.add(arr[i]); + } + } + // Handles the case when k = 0 + // or lists have no elements in them + if (queue.isEmpty()) { + return null; + } + // Loop till 'queue' is not empty + while (!queue.isEmpty()) { + // Get the top element of 'queue' + Node curr = queue.poll(); + + // Add the top element of 'queue' + // to the resultant merged list + + last.next = curr; + last = last.next; + // Check if there is a node + // next to the 'top' node + // in the list of which 'top' + // node is a member + if (curr.next != null) { + // Push the next node of top node + // in 'queue' + queue.add(curr.next); + } + } + // Address of head node of the required + // merged list + return head.next; + } + + // Print linked list + public static void printList(Node node) { + while (node != null) { + System.out.print(node.data + " "); + node = node.next; + } + } + + public static void main(String[] args) { + int N = 4; + // array to store head of linkedlist + Node[] a = new Node[N]; + // Linkedlist1 + Node head1 = new Node(1); + a[0] = head1; + head1.next = new Node(2); + head1.next.next = new Node(3); + // Limkedlist2 + Node head2 = new Node(4); + a[1] = head2; + head2.next = new Node(5); + // Linkedlist3 + Node head3 = new Node(5); + a[2] = head3; + head3.next = new Node(6); + // Linkedlist4 + Node head4 = new Node(7); + a[3] = head4; + head4.next = new Node(8); + + Node res = mergeKList(a, N); + + if (res != null) + printList(res); + System.out.println(); + } +} \ No newline at end of file diff --git a/Searching&sorting/prob17.class b/Searching&sorting/prob17.class new file mode 100644 index 0000000000000000000000000000000000000000..727a3135f92712e007847a054f26cd93b19e4ec2 GIT binary patch literal 662 zcmY*XO=}ZT6g@BVm5h^QG;OR+(yCQSQ|aJBx@Z#+K?tNyAtDUjI7!FyYBCdMCWY?% zL&S|6H@eUw(jVZDaVaSHaVAl!v$*%pedpeD&b;~j^W!;yE!;6-pkiVHizakb3%H6U z6W6e8pk|;hpzp{~rX2yLx&Bl@eHa}C0_C0zgU8eHAc&v%gAqFm&t;sXyD~{+c(@lO zGL^?{>&^XccfBi6?5F^mbrJaqbL%<1in$m~bcco;mA z+44)1I2zpB+RTs^@+cT+SXjZT1q($3*Dc(@O#^EdZs9gr=Xe48Vz)au3Wn+5)-;tP z=Rq9%Ckag@QOpyKS~Kc@hWaN-8jNW^ni8-$mntJ?k2+JT4gB%8KxM}Ae_OzqWS|jE zs!i^tLY*HwdlZPw1f$8f2D4z+S|1?ZvY=l^eby`xMvJU7=riP?GOxDIkW<@Ar%`)_ zN~^J1e+m6GCr%ad`q!8G8$xokB`Y&Vi$g^&EHRdO*EVmtMBWM`h*N$bFGT4(G_sX> zJZB3yma(<%{3p{>G}lvg*VF88uBY3q3_I_7dDZo7-TumG*k!l3ao*mjpF!!ogW7lx c?ZQx%>p|wbSc1b}>^_#UgBr;$&-7mT4G@!iy8r+H literal 0 HcmV?d00001 diff --git a/Searching&sorting/prob17.java b/Searching&sorting/prob17.java new file mode 100644 index 0000000..aa25e1c --- /dev/null +++ b/Searching&sorting/prob17.java @@ -0,0 +1,28 @@ + +/** + * + * Find the smallest positive number missing from an unsorted array + * + */ +import java.util.Arrays; + +public class prob17 { + // method1 simple + public static int firstMissingPositive(int[] nums, int n) { + Arrays.sort(nums); + int ans = 1; + for (int i = 0; i < n; i++) { + if (nums[i] == ans) { + ans++; + } + } + return ans; + } + + public static void main(String[] args) { + int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }; + int n = arr.length; + int ans = firstMissingPositive(arr, n); + System.out.println(ans); + } +} diff --git a/Searching&sorting/prob18.java b/Searching&sorting/prob18.java new file mode 100644 index 0000000..fdc4914 --- /dev/null +++ b/Searching&sorting/prob18.java @@ -0,0 +1,172 @@ +import java.util.PriorityQueue; + +/** + * K maximum sum combinations from two arrays + * + * + */ + +public class prob18 { + // method 1: + // function to display first K + // maximum sum combinations + static void KMaxCombinations(int A[], int B[], + int N, int K) { + // max heap. + PriorityQueue pq = new PriorityQueue( + Collections.reverseOrder()); + + // Insert all the possible + // combinations in max heap. + for (int i = 0; i < N; i++) + for (int j = 0; j < N; j++) + pq.add(A[i] + B[j]); + + int count = 0; + + while (count < K) { + System.out.println(pq.peek()); + pq.remove(); + count++; + } + + } + + // Driver Code + public static void main(String[] args) { + int A[] = { 4, 2, 5, 1 }; + int B[] = { 8, 0, 5, 3 }; + int N = A.length; + int K = 3; + + // Function Call + KMaxCombinations(A, B, N, K); + } + + // method 2: + + public static class Pair { + + public Pair(int l, int m) { + this.l = l; + this.m = m; + } + + int l; + int m; + + @Override + public boolean equals(Object o) { + if (o == null) { + return false; + } + if (!(o instanceof Pair)) { + return false; + } + Pair obj = (Pair) o; + return (l == obj.l && m == obj.m); + } + + @Override + public int hashCode() { + return Objects.hash(l, m); + } + } + + public static class PairSum + implements Comparable { + + public PairSum(int sum, int l, int m) { + this.sum = sum; + this.l = l; + this.m = m; + } + + int sum; + int l; + int m; + + @Override + public int compareTo(PairSum o) { + return Integer.compare(o.sum, sum); + } + } + + public static void MaxPairSum(Integer[] A, Integer[] B, int N, int K) { + // sort both arrays A and B + Arrays.sort(A); + Arrays.sort(B); + // Max heap which contains Pair of + // the format (sum, (i, j)) i and j are + // the indices of the elements from + // array A and array B which make up the sum. + PriorityQueue sums = new PriorityQueue(); + + // pairs is used to store the indices of + // the Pair(i, j) we use pairs to make sure + // the indices does not repeat inside max heap. + HashSet pairs = new HashSet(); + + // initialize the heap with the maximum sum + // combination ie (A[N - 1] + B[N - 1]) + // and also push indices (N - 1, N - 1) along + // with sum. + int l = N - 1; + int m = N - 1; + pairs.add(new Pair(l, m)); + sums.add(new PairSum(A[l] + B[m], l, m)); + // iterate upto K + for (int i = 0; i < k; i++) { + PairSum max = sums.poll(); + System.out.println(max.sum); + l = max.l - 1; + m = max.m; + + // insert only if l and m are greater + // than 0 and the pair (l, m) is + // not already present inside set i.e. + // no repeating pair should be + // present inside the heap. + if (l >= 0 && m >= 0 + && !pairs.contains(new Pair(l, m))) { + sums.add(new PairSum(A[l] + + B[m], l, m)); + pairs.add(new Pair(l, m)); + + } + + l = max.l; + m = max.m - 1; + + // insert only if l and m are + // greater than 0 and + // the pair (l, m) is not + // already present inside + // set i.e. no repeating pair + // should be present + // inside the heap. + + if (l >= 0 && m >= 0 + && !pairs.contains(new Pair(l, m))) { + // insert (A[i1]+B[i2], (i1, i2)) + // in the heap + sums.add(new PairSum(A[l] + + B[m], l, m)); + pairs.add(new Pair(l, m)); + } + + } + + // Driver Code + // public static void main(String[] args) + // { + // Integer A[] = { 1, 4, 2, 3 }; + // Integer B[] = { 2, 5, 1, 6 }; + // int N = A.length; + // int K = 4; + + // // Function Call + // MaxPairSum(A, B, N, K); + // } + } +} diff --git a/Searching&sorting/prob2$pair.class b/Searching&sorting/prob2$pair.class new file mode 100644 index 0000000000000000000000000000000000000000..92095816ef0c3b21883b105f5633987b695e72fc GIT binary patch literal 344 zcmX9(xlY4C6rA-DA1v5}`zRXNY;u%*LL?_^Sjp)c_D3g_#6E*SgF{O|%N8UJo19s!qmE literal 0 HcmV?d00001 diff --git a/Searching&sorting/prob2.class b/Searching&sorting/prob2.class new file mode 100644 index 0000000000000000000000000000000000000000..66385d3628518e142bdb5a912e387e6382c44934 GIT binary patch literal 1698 zcmaJ>OK%%h6#lL~wvwzTQPZ6GyuW9r1E4yjB8%EZ1&rm<%% z&o~f?Wh8d2VO6OcmQ@i-suor3kXXTr1%e+^%Hzx<^@K#oEBqU^rNII6&&M@W-sTkSDogp2=1kM~G_p>t2;k=AE-j;Ad z!bJw5rRi-3rDzzuoo{HC#Vv-&HQmtdX@+oWe33wTv(6d%O1i=4JIxi|UeHz=WQnip zM!jHm+BX}#$qk!arPNZfSaiI4E4EhKnA2K5SZHdx!7z|oD&5yMwQNH(*0L45ts84O z2QOEMsKyJr!z{Pj=F0hu17zr#=axOkoxqlYV^A6TU5bvaH?p&uwN6naOerML?;9blpxPci7c?Iv`CKYnSG;PanYppqMubXwNFM>i8w-n5x zDB*ntw^34X948n=H#PFjfzo|Mju=y( zV&PVYNG_)WAdfkB&=O?wK_pboG;C7Yy3My3)I*5IKcc3taSC(#u(t=}P6 zq=R8`3Q^xzd}YhBd6Q^OCwtYS(9P@}>a0!uJM>A6@=v}Q56RtA~~5>g-lu%Gs{mP zJcC$O1y$TdWCzl{ZIONR&u`lTjX!qXzYMs4{>pnQGC8D1>O``G=-2qTyNmq*@v3w} z`VO)xJV4%Ci4SnaS@k%!thXXt@>?i-oM{)Cai^ZlQ}hBmc!+HJ;3)mxAlY&>&(QuBA?}hkpO88_PU2H~`vpevh=l$bN&G_ZekIKB^kqItj0wd4 zLXU(Hdx>850%I>AzVvs0;xpROgBS)evnK}_<$_sbC#l?!x%1L5*LYc*sXAcG6wDFZc$C3 ZnnJXS(;USeRPX^+Hc9p mp = new HashMap(); + for (int i = 0; i < n - 1; i++) { + for (int j = i + 1; j < n; j++) { + mp.put(arr[i] + arr[j], new pair(i, j)); + } + } + for (int i = 0; i < n - 1; i++) { + for (int j = i + 1; j < n; j++) { + int sum = arr[i] + arr[j]; + if (mp.containsKey(X - sum)) { + // Making sure that all elements are + // distinct array elements and an + // element is not considered more than + // once. + pair p = mp.get(X - sum); + if (p.first != i && p.first != j && p.second != i && p.second != j) { + System.out.print( + arr[i] + ", " + arr[j] + ", " + + arr[p.first] + ", " + + arr[p.second]); + return; + } + } + + } + } + } + + // method 2 withoud duplicates + public static void fourSum(int X, int[] arr, + Map map) { + int[] temp = new int[arr.length]; + + // Iterate from 0 to temp.length + for (int i = 0; i < temp.length; i++) + temp[i] = 0; + + // Iterate from 0 to arr.length + for (int i = 0; i < arr.length - 1; i++) { + + // Iterate from i + 1 to arr.length + for (int j = i + 1; j < arr.length; j++) { + + // Store curr_sum = arr[i] + arr[j] + int curr_sum = arr[i] + arr[j]; + + // Check if X - curr_sum if present + // in map + if (map.containsKey(X - curr_sum)) { + + // Store pair having map value + // X - curr_sum + pair p = map.get(X - curr_sum); + + if (p.first != i && p.sec != i + && p.first != j && p.sec != j + && temp[p.first] == 0 + && temp[p.sec] == 0 && temp[i] == 0 + && temp[j] == 0) { + + // Print the output + System.out.printf( + "%d,%d,%d,%d", arr[i], arr[j], + arr[p.first], arr[p.sec]); + temp[p.sec] = 1; + temp[i] = 1; + temp[j] = 1; + break; + } + } + } + } + } + + // Driver Code + // Program for two Sum + public static Map twoSum(int[] nums) { + Map map = new HashMap<>(); + for (int i = 0; i < nums.length - 1; i++) { + for (int j = i + 1; j < nums.length; j++) { + map.put(nums[i] + nums[j], new pair(i, j)); + } + } + return map; + } + + public static void main(String[] args) { + int arr[] = { 10, 20, 30, 40, 1, 2 }; + int n = arr.length; + int X = 91; + + // Function call + findFourElements(arr, n, X); + + /** + * + * int[] arr = { 10, 20, 30, 40, 1, 2 }; + * int n = arr.length; + * int X = 91; + * Map map = twoSum(arr); + * + * // Function call + * fourSum(X, arr, map); + */ + } + +} diff --git a/Searching&sorting/prob3.class b/Searching&sorting/prob3.class new file mode 100644 index 0000000000000000000000000000000000000000..68f2f2a04a9c40d7e3279f920708f7157c7bb157 GIT binary patch literal 1888 zcma)7&r{n*6#f=VURxI601iI_385shf#NhNqzx%0aZ7P)FfEjp&>vab3sI0Ik0dkY z-g~d@HJ4m+XnROWrpe^o>7UWRqBCv!BrCBzFqzJ1w7YNLe(&4wy(j(g?~`W$uEEgI zhY1aDU^0aZxY$S5nH1i{EJt3$WxVC@UGZO6HKg&jhEteJVjkBLct^v#xSqfQ#|@76 zI2IY=Hw?@0XcEijwiuLxU6TyGCBu?y&3Z*To1$WpMKj!W+jWg#k<9KCcZ$Vg?lwdB zh9|1~tD+G)Ds^F445za@rF-H)dodpWNVK<$sTs8tO4acrro%P{$^kabIrjA=EaD1TSLo73-Z`rozdX8wU zO7E^+b9>|XD2){wifNqF@i9K(DCtXYHg$ZCEggdx;`llU0wDhz1XJBBY(-OYf#R`nAlFhjaA?`{6p=87JCTRK308*rTE<+4g?3L0T0p zOF9KpxUMAW{)~nU@ml?~BCMJz-O1L$h2zX3mX3p)hYcBZ|NoneO#wztDs}g!GOFMvjF4 z@u0cy`U7HQ2Uezz(DfKGh9?Au$56ZQ9P#VQuyO=`gv9g_lCgO;qmJIk=&+JeuRMY_ zol$4+jNOMCd-%P|9=!NVc}Q4YL9_{q10*SuhH<1Y37vir-B?5qmT10A|Ak@l=tk@x zT;hncp}(Qhff1Yu$^A%FRB|cCf7iBSYI$2x%G+wZTng4{PKI=XEa_x= K. + * + * Input : a[] = {1, 2, 2, 1}, + * b[] = { 3, 3, 3, 4 }, + * k = 5. + * Output : No + * + * + */ +public class prob3 { + static boolean isPossible(int a[], int b[], int n, int k) { + Integer[] newA = Arrays.stream(a).boxed().toArray(Integer[]::new); + Arrays.sort(newA, Collections.reverseOrder()); + Arrays.sort(b); + for (int i = 0; i < n; i++) + if (newA[i] + b[i] < k) + return false; + + return true; + } + + public static void main(String[] args) { + int a[] = { 2, 1, 3 }; + int b[] = { 7, 8, 9 }; + int k = 10; + int n = a.length; + + if (isPossible(a, b, n, k)) + System.out.print("Yes"); + else + System.out.print("No"); + } +} diff --git a/Searching&sorting/prob4.class b/Searching&sorting/prob4.class new file mode 100644 index 0000000000000000000000000000000000000000..1190c8f64aa82a5953234866a26e3150b0c6cf12 GIT binary patch literal 1572 zcmaJ>L2MgE6nzt~ch>7Q**e}dX~A{dq;;A&DKu+|uFiPqQN3E7z*w{n5jlFBx zn}~4Y5OG1`NI4;hgn9)IsZ^>QKnTR4*NO|AdPL&H1%&ytn~+4Qu&tfHf8KlZ=gs*4 z{Lh1309R4gk;VweXyOBUPvI0!XDK+Nqkyv<=X7w4XgDv&F^+Kt^<~fZ!dDp*#fh5? zN+oCthQS5T7uVO@E26vPuCyqlzw7zUO3-cxK0~UwT$NwR$kao(v9{=TA|S^F5^1|0 zp@xgg3wPWNcc$g~t26bm>-no?Nzv=Udbc6wy-2vz4OV8SCD4F@48w^7Qq>Q|s_1fD zG*H9@gZWwzguSrqb{0i=J81R>Rb0|AXY2%#Rbt4ZQ+N#g4-1Z z113(8)WI^fl{=ylG7KzNkL2r{y->8tn_!)0t#~(HFmr>p64Hi*+a|}K#|uPd1%{Jt zcTH3Rzu|_ryzn+fz0jp)iCe5r95;huC@SKpWK=#aAX&#b6E``o$n9Qb7(3X4=WhgS zV$bEcgn73S2Hj1LYjn&DL9n*oVKAz`FS?bM+v^Fc>(j$4>}kZ#zTx`KmgtSe#Pab% z4rPuImo_`%De%L0A@;j`*pWSnirZ?{y-<`n<`~A0?eA%|G35UrhqH9u)AT<85+DnZ zq31L7_8g6j#^j~@U|&-}H=mwrluS@W7lmSivhRtSp)r-Pm4uy4*y`l2&8K#4t+Z>W zvI)mF96N36mSXX3Jh76NwvAsc)k_C;Vt;=~kEfKast8XRQ zmegI^m)OQ&42(*9WnYfcF_Q@Q`WN>2l6gwnH4xeLKJpYNsokh#5hu$uSkQ5XoSvo3 z>tx`YWaZm5^A3j4K@J-@iH|UXFEEO)s7>wQG#=tvd`D;U1L^%l>_^nJexbAb4d?I# z=kW)|@F&LcH!iXP6q$w+WOpkf)hBp{gL4eUKeqn?a+YQNg2%)tscM*BsT%)f{dXYmR2#s5z!e&qY&}FjFO*$t935a)N;L z(9CA-x|xy?iHHD$|0(4qV17@@F(ZblneWx+6gstRN*>o#X;j&PesCM}WGSf0Xt+Yn rZ5D6gMSMuT{$pIjCzzvqIZX2dWT;J}PTQNsON1FEJ3%ZKUGx0E`*2`A literal 0 HcmV?d00001 diff --git a/Searching&sorting/prob4.java b/Searching&sorting/prob4.java new file mode 100644 index 0000000..9758e7c --- /dev/null +++ b/Searching&sorting/prob4.java @@ -0,0 +1,59 @@ +// Find common elements in three sorted arrays + +public class prob4 { + void findCommon(int arr1[], int arr2[], int arr3[]) { + int i = 0, j = 0, k = 0; + int n1 = arr1.length; + int n2 = arr2.length; + int n3 = arr3.length; + int prev1, prev2, prev3; + prev1 = prev2 = prev3 = Integer.MIN_VALUE; + + while (i < n1 && j < n2 && k < n3) { + while (i < n1 && prev1 == arr1[i]) { + i++; + } + while (j < n2 && prev2 == arr2[j]) { + j++; + } + while (k < n3 && prev3 == arr3[k]) { + k++; + } + + if (i < n1 && j < n2 && k < n3) { + if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) { + System.out.print(arr1[i] + " "); + prev1 = arr1[i]; + prev2 = arr2[j]; + prev3 = arr3[k]; + i++; + j++; + k++; + } else if (arr1[i] < arr2[j]) { + prev1 = arr1[i]; + i++; + } else if (arr2[j] < arr3[k]) { + prev2 = arr2[j]; + j++; + } else { + prev3 = arr3[k]; + k++; + } + } + + } + } + + // Driver code + public static void main(String args[]) { + prob4 ob = new prob4(); + + int ar1[] = { 1, 5, 10, 20, 40, 80, 80 }; + int ar2[] = { 6, 7, 20, 80, 80, 100 }; + int ar3[] = { 3, 4, 15, 20, 30, 70, 80, 80, 120 }; + + System.out.print("Common elements are "); + + ob.findCommon(ar1, ar2, ar3); + } +} diff --git a/Searching&sorting/prob5.java b/Searching&sorting/prob5.java new file mode 100644 index 0000000..3bc9a97 --- /dev/null +++ b/Searching&sorting/prob5.java @@ -0,0 +1,73 @@ +/** + * Searching in an array where adjacent differ by at most k + * + * + * Input : arr[] = {4, 5, 6, 7, 6} + * k = 1 + * x = 6 + * Output : 2 + * The first index of 6 is 2. + * + * Input : arr[] = {20, 40, 50, 70, 70, 60} + * k = 20 + * x = 60 + * Output : 5 + * The index of 60 is 5 + * + * + */ +public class prob5 { + // x is the element to be searched + // in arr[0..n-1] such that all + // elements differ by at-most k. + static int search(int arr[], int n, + int x, int k) { + int i = 0; + while (i < n) { + if (arr[i] == x) { + return i; + } + // Jump the difference between + // current array element and x + // divided by k We use max here + // to make sure that i moves + // at-least one step ahead. + i = i + Math.max(1, Math.abs(arr[i] - x) / k); + } + return -1; + } + + static int searchAtmost1(int arr[], int n, int x) { + + // Traverse the given array starting + // from leftmost element + int i = 0; + while (i < n) { + + // If x is found at index i + if (arr[i] == x) + return i; + + // Jump the difference between current + // array element and x + i = i + Math.abs(arr[i] - x); + } + + System.out.println("number is not" + + " present!"); + + return -1; + } + + // Driver program to test above function + public static void main(String[] args) { + + int arr[] = { 8, 7, 6, 7, 6, 5, 4, 3, + 2, 3, 4, 3 }; + int n = arr.length; + int x = 3; + System.out.println("Element " + x + + " is present at index " + + search(arr, n, 3)); + } +} diff --git a/Searching&sorting/prob6.class b/Searching&sorting/prob6.class new file mode 100644 index 0000000000000000000000000000000000000000..07feb6d72cd50b56f276f7b755e1c82160180eb6 GIT binary patch literal 1455 zcmaKs-*4Mg6vw~UvEww&RyQGCN0Keux-~!6WE)!tOIy$)O;l= zw{5zQ<#v~rc-yqPO;ft<9f4S3Yn{L1y1==nFWbADvOn^hKJ~l9bUkU=0&|6}jaTxu ztahdSvfA`r%YIoaKGAVq#|`FgI(u&0d}M_e^<8Isxe~Z1Fok#m2F~kPOrU_Gfbr0A ze9w1ff7A4LoQ^jWMJa}I0ynXwqmn=sw_>;*JQF|*voY-S`o{Jvv+WC{&R`Nywpi4d zcXQwK%^u}(_85~MmSH*7&sl@dN=(_S#qj~|3S6sGB371nUgSl-$YvW z^{(_hlVyB6jx)+J?A52z?sQFWVHjAO#2B-@6Zm+)Z=T^k-oRm3YvZ+zQq*O)+q8VM zrej6m`b2$au?bxIe?MH|V8u96fXZ>=d&+g1PdV;_yH@%I;zu5+57%gDoMOm1oaZ@k z{feO)_XoMm0kq5@v#h4o>|2yeX|I znEwV5z}yzo(^vzSK`8Kkji{|!YLa~gR#T_c`v5E=56j=zJZ z3^LgRR5RI3N9#UcRzs38sJECVN@w+Oh_rHe@<-;BrxI3pnfdbMDUz{7lADxgiIys7 z`4<0oaSzMnx*u{SLauo+^A}Ww^~{ogsMHT5rM@uq-{P%^+Gwd-qoo8!bIp zVn(9TGNMMRu~9x=HDYV!NLKCSeuWa~s=Pt+Cq!~bOogAJ9U>JxmMQNMyAzm#ZVlDE z8n(8EMXZo}mCS3T{Fv(}*u+CTLp>x;K{=s8(~;8gp5T1Z9ATkBqB({HVhfh|fF)jJ PGeEHwWNFKV>y>{2FX%rd literal 0 HcmV?d00001 diff --git a/Searching&sorting/prob6.java b/Searching&sorting/prob6.java new file mode 100644 index 0000000..281c29e --- /dev/null +++ b/Searching&sorting/prob6.java @@ -0,0 +1,68 @@ +/** + * Ceiling in a sorted array + * + * Given a sorted array and a value x, the ceiling of x is the smallest element + * in array greater than or equal to x, and the floor is the greatest element + * smaller than or equal to x. Assume than the array is sorted in non-decreasing + * order. Write efficient functions to find floor and ceiling of x. + */ +public class prob6 { + // method1:linear search + static int ceilSearch(int arr[], int low, int high, int x) { + int i; + if (x <= low) { + return low; + } + for (i = low; i < high; i++) { + if (arr[i] == x) { + return i; + } + + if (x > arr[i] && x <= arr[i + 1]) { + return i + 1; + } + } + return -1; + } + // method 2 : binary search + + static int ceilSearch2(int arr[], int low, int high, int x) { + // base condition if length of arr == 0 then return -1 + if (arr.length == 0) { + return -1; + } + /* + * this while loop function will run until condition not break once condition + * break + * loop will return start and ans is low which will be next smallest greater + * than target + * which is ceiling + */ + while (low <= high) { + int mid = low + (high - low) / 2;// calculate mid + + if (x == arr[mid]) { + return mid; + } + if (x < arr[mid]) { + high = mid - 1; + } + + else { + low = mid + 1; + } + } + return low; + } + + public static void main(String[] args) { + int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; + int n = arr.length; + int x = 8; + int index = ceilSearch2(arr, 0, n - 1, x); + if (index == -1) + System.out.println("Ceiling of " + x + " doesn't exist in array"); + else + System.out.println("ceiling of " + x + " is " + arr[index]); + } +} diff --git a/Searching&sorting/prob7.class b/Searching&sorting/prob7.class new file mode 100644 index 0000000000000000000000000000000000000000..3a5e905342608408246ac059bfdd472f12f7034a GIT binary patch literal 1728 zcmaJ>T~ixX7=8}fWW%y0Av9v;!?Xnqp%9@ht)yUWS|k<-8m3I_IOCEWU`yD|BpYV9 z(5wCky{gk2Z#vG@>ClQ!#|y8#^9T4xI!^UDn;=0t?!`IhefRx%p69%~zrQ|w3E&#m z48)M=#CcqZ(J^Y^JtV^z(~&X|Lc)N7ado<+V?r5|%1Eo_{TKvB!nKds+_h{+;H~8Sr3coYm9ALMR=VKTY-cN@dKv|{Q7g#>TlF!jHFx9M zqzW|Ai?cdrO!B@i5WVHPUfru%)n(~zyXAT$gb%`)HIcy$9djn;@u7gZ;wI{i(srWi zgYEHKHaxqMUbO1lL}ub9J~D9&S%KzTA5hNmWNLa z;gn6hgMNXa50tQuIpsGV$dY%$RoJh4a+m754Zess1+d-pD%pF~Kw7&Q1E1ioz*)b= zf@(3FNG8Okgh-4D^zB+ZGV3}e%Uid-ZJz3$<#=@^D6iqPqyoJ@q?28I!0bs7$7p#)!*7kLL z#sOV&-JJ#})yz4LtYs@!y)LQiH|?}qHJT&0XgTGItPeL6+qt&JxsCma#I^mZd_#Eq z2XVyjbcw80sT6EaW^@z;Mo#g26E=aN|BvGzq=&x}^=SMr@Jr(wr!~l3a1W-QLpj6z)Fx;z-y9wD8IYm=$L$#VZAM7S%n z-2WZ=endyhJVXFEfTlh9H})|)A8O+Jzn?t}aQ%U?u^=M?PuQx%2Q!H-o;#Up5>SNb zqnIL}EKhgH+Y9HUJHUn4ApNcQ#wnahv3MdMGBP&B?Kjh_)JK8L;% zn9+P5=?Mkv1;R&rfae2r{tDv&UD}tvWv=^p|2R(SS6R)MXTHTbMVF2N-+PE|pYhXX zlA;$OJtcLM-88WR?~>hl^1MJk7ctBICPtCt|GtPM9HijVZeRjmA?-7aD~8=dM@YQF z)L-Zj map = new HashMap(); + for (int i = 0; i < n; i++) { + map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); + } + + for (int i = 0; i < n; i++) { + if (map.containsKey(d + arr[i])) { + System.out.print("Pair Found: (" + arr[i] + ", " + + +(n + arr[i]) + ")"); + return; + } + } + System.out.print("No Pair found"); + + } + + public static void main(String[] args) { + int arr[] = { 1, 8, 30, 40, 100 }; + int n = -60; + findPairMap(arr, n); + } +} diff --git a/Searching&sorting/prob8.class b/Searching&sorting/prob8.class new file mode 100644 index 0000000000000000000000000000000000000000..c425308129ae0d3764c853cabcb03e5c9306aa69 GIT binary patch literal 994 zcmZvZ+fEZv6o&uZ&UD&gS}HgQrR7xAf~HmCF&vEXSR$s>Qh~W?vjHrlVG=w-3 zD%~*^lAvqUX5^ISl>Q(rd)`X5_0^GT~(GVN8PRG|_n z*IPAb)wUWH(`jB7kW<<03=4$wj!}NGY&8BGILDGz!>S1krPdyA8ZV7Z#i(s$@{VoQ zHs;-y!G&_A%b@1#ExT;qx7?0u!>*TZq}?11eb6+7pejgen8sNJ=QNy0O2Yu63T8CS z;sT+(9D!)BQ?9gWmYv^H%dsk%+qP|NHA&X2+q{ueYgrfML{fgM>6leMO1;GZ{TSS; zXI4n9Io3gP2fjp_Mwik> z_amo^qa6g=KGBxN_R*KNMEkMrr`?UeW>p{DzOx>pMlVdr2!`2zngsJWg(aTvQhUU^ z73fre5h#a{g!q9z{=;JYJLKaZ(Yc&1`c4=98BzA&?+tLz8-V!amUOuTm-!#?R|vJ` zqwS-wah+l7#YK<)vq!&wf_{$A>M{i|%Jy**CNP9CdgGYF1a5L2w~)jG&a}+?JW}2i zgOCrQ3UP?25Xo-{a|CW{5U0ERbL982^gvWw*nvdGgV8<6?-A&&EW#KdO`BoSO9asW uZ21Z#-U0F82esf2<_eOOE69OdA)w?6N>s_cgRfWVc=;jr9%7CUXMO={X0sar literal 0 HcmV?d00001 diff --git a/Searching&sorting/prob8.java b/Searching&sorting/prob8.java new file mode 100644 index 0000000..e0f7759 --- /dev/null +++ b/Searching&sorting/prob8.java @@ -0,0 +1,49 @@ + +/** + * + * Count triplets with sum smaller than a given value + */ +import java.util.*; + +public class prob8 { + static int arr[] = new int[] { 5, 1, 3, 4, 7 }; + + static int countTriplets1(int n, int sum) { + int ans = 0; + for (int i = 0; i < n - 2; i++) { + for (int j = i + 1; j < n - 1; j++) { + for (int k = j + 1; k < n; k++) { + if (arr[i] + arr[j] + arr[k] < sum) + ans++; + } + } + } + return ans; + } + + static int countTriplets2(int n, int sum) { + Arrays.sort(arr); + // Initialize result + int ans = 0; + for (int i = 0; i < n - 2; i++) { + int j = i + 1; + int k = n - 1; + while (j < k) { + if (arr[i] + arr[j] + arr[k] >= sum) + k--; + else { + ans += (k - j); + j++; + } + } + } + return ans; + + } + + public static void main(String[] args) { + + int sum = 12; + System.out.println(countTriplets2(arr.length, sum)); + } +} diff --git a/Searching&sorting/prob9$Pair.class b/Searching&sorting/prob9$Pair.class new file mode 100644 index 0000000000000000000000000000000000000000..ff32be1c8c8c9806866d5de76f36fb50f9611a6d GIT binary patch literal 344 zcmX9(OH0E*7@WM?P%yJy;mDu?C>>XpjnZP8tps?M&?7wLN{;7+A(?rPmQI0)e3 zFhCDZ02dBpo%8H5EfmZDDM+eHs!5q@Eww<@){M)vdL2Jx3z_qec9#+`hoc!zxrNQu z3?3E}(RLFBj|ZQ;L3KfgNe<&ri1>I7BR*Nf{OF7Ualj&Aix@H%QS}+v literal 0 HcmV?d00001 diff --git a/Searching&sorting/prob9.class b/Searching&sorting/prob9.class new file mode 100644 index 0000000000000000000000000000000000000000..8fbfc363dea6fb1a49150b1f0d59a2ddb89b20f9 GIT binary patch literal 2184 zcmaJ?U2_vv7=AX{?55iVLTd`82oc+weyd>lNGX;|Z6s;XATbn$O|os5rn_->!%(jo zue|V1<;EGjU>tAMaS8(t!?i!a8UKejI08OrleUReXJ^kjd)}|-eV_N7{q5ODTd=>?}QjmsyHQNDX~4(fzz1opwSsI zyxm3b?`SxOISsvdH;Q>Nr&YYC;=Ba;f?>H5^t5f8?rhcYJkyh)Oj)+&PfG|Vhb~cR z)~T2h_GB#ET&S;=O!uNus&Z%7l4V!&_0o*%8tb$>kX%fshcefV8^%Q4x2h9?AY*xc zipqK4D6eLXT41aqBcUU2E!&1)cj+tnpSDw(n(LHK_6w+~X?lv(T+8+)>`(3(NiQL2he?WlQKuE;f8s4SRVa?=!%1O31amQ+LbeoF($r0wCieKM9=+rsro(Q4UYX z%Qz%q?{?<%hPT38C3J7^ZB=8_Q;?Fd&FWY{PR9kjuj2!;%HyJr4{=GX3Y(q-aB15& zmrYm4M?zY}WfhA$uHa)GpWv#FYq%;QcGhux&v%Vl*7R4Linm9B5k*Ny85I?#jwLMX zcm+o!bS*duuU;|)i3#&2*)GD!aXnsjX&Lab2_rv+3XF+p=#st7h{= zG*HYLW#4hvRXEHh<2b8zw)xksdV351|yp@yI=>8;BN~2B(zKxO^WS8_>SN%;viDG2~N9cv6k4y~+mkI~WYidzCni zcRj}L4eXJxZ8^K8N_U_CPH7}?6)iLz3ENoVR)oUZ*pGx83KE*bUasRzpcgUpp&JMJ z9L4}%#W4DD5`#F45ng6vyphIXVFI6X{sKqw6^`LMYJZPOYJ+d&IeMU|=$BN4RLE?0 z9C?ZXvHT08PpCW)gdSu-UPz4!qJl6VU@Sb(@f1ce6JY8<=x>A=e5e_D2pvppq)GF)q+JkyCD!?? zRt(3KTv6s53FV4P>}js3s<~n`_AFP7DG?6hGZqzEv5wfE9JSb!TxR6a>5+r?(X%i{ z?6 findSubArrays(int[] arr, int n) { + HashMap> map = new HashMap<>(); + + // create an empty vector of pairs to store + // subarray starting and ending index + ArrayList out = new ArrayList<>(); + // Maintains sum of elements so far + int sum = 0; + for (int i = 0; i < n; i++) { + + // add current element to sum + sum += arr[i]; + + // if sum is 0, we found a subarray starting + // from index 0 and ending at index i + if (sum == 0) + out.add(new Pair(0, i)); + + ArrayList al = new ArrayList<>(); + + // If sum already exists in the map there exists + // at-least one subarray ending at index i with + // 0 sum + if (map.containsKey(sum)) { + // map[sum] stores starting index of all subarrays + al = map.get(sum); + for (int it = 0; it < al.size(); it++) { + out.add(new Pair(al.get(it) + 1, i)); + } + } + + al.add(i); + map.put(sum, al); + } + return out; + + } + + // Utility function to print all subarrays with sum 0 + static void print(ArrayList out) { + for (int i = 0; i < out.size(); i++) { + Pair p = out.get(i); + System.out.println("Subarray found from Index " + + p.first + " to " + p.second); + } + } + + // Driver code + public static void main(String args[]) { + int[] arr = { 6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7 }; + int n = arr.length; + + ArrayList out = findSubArrays(arr, n); + + // if we did not find any subarray with 0 sum, + // then subarray does not exists + if (out.size() == 0) + System.out.println("No subarray exists"); + else + print(out); + } +} \ No newline at end of file diff --git a/Searching&sorting/temp.class b/Searching&sorting/temp.class new file mode 100644 index 0000000000000000000000000000000000000000..52c601f8ff4d85e3fadda4c2c04ec453da4e40cc GIT binary patch literal 539 zcmY*V%T5A85UgQW2G&Io-{|^&peAzkppqC86B2wR7%!fNWrM4*5L`^W`z2mH>j4uF zetpP zzz>T8Mt<``z$~@vo7Husk?&rq z?jZqYzPwoy7>iT~VFI$FNlku(hF#FKFESQJ3ULl@Y2-uAAsA&+G z!U$^(bz#6{Ud_fT#(`0Ew)-$1G4%p-+v#H{qw0Oc9}MyI^QkArqDeW<;&^i7j1pcount is odd + mid = mid.prev; + } + + /* move head to point to the new DLLNode */ + head = new_DLLNode; + + } + + /* Function to pop an element from stack */ + int pop() { + /* Stack underflow */ + if (count == 0) { + System.out.println("Stack is empty"); + return -1; + } + + DLLNode head = head; + int item = head.data; + head = head.next; + + // If linked list doesn't become empty, update prev + // of new head as NULL + if (head != null) + head.prev = null; + + count -= 1; + + // update the mid pointer when we have even number of + // elements in the stack, i,e move down the mid pointer. + if (count % 2 == 0) + mid = mid.next; + + return item; + } + + // Function for finding middle of the stack + int findMiddle() { + if (count == 0) { + System.out.println("Stack is empty now"); + return -1; + } + return mid.data; + } +} diff --git a/Stack/Probs/SQ11.class b/Stack/Probs/SQ11.class new file mode 100644 index 0000000000000000000000000000000000000000..a58d398d60946cfab7e110a65bc23efc0d491e81 GIT binary patch literal 925 zcmZuvO-~b16g{u)bm%a&MJV!Nm2XFeT$=0B+)yzr(<32_VoXC9#x+b}QpJ>tgg`K7*_OK~;7=sC1OiLd*QP*Z)w0d? zdS%aMYGq|1g~N*COk zWtSFYcdbyZ*NWzfB|C-+PcoSqS*Ig{D2IBOx@(n*VP73dOzXIbl#W}N(UHciKzFNi z-geEBS<{ihZ54Am?qFU=4|-K(b&7M3MCA~HXbZHly=xX-0d?Of*UgPLl5RfP#`m)8 z0>MswZ%1G<(RSN}FSG+LQ*3GNJ*qhFfhXp3TBqs=^d|mW++o@7mZacSQ_MDwg@ZlU ztni{*C(~GSyj4vr=B^>~l^H%$_bEGqLG=zUI$;f$!M~{A+>5crb=xji5DHW!mz(d+4 MO1w-|zsGjq0-|}hr2qf` literal 0 HcmV?d00001 diff --git a/Stack/Probs/SQ11.java b/Stack/Probs/SQ11.java new file mode 100644 index 0000000..a435c1c --- /dev/null +++ b/Stack/Probs/SQ11.java @@ -0,0 +1,69 @@ + +/** + * + * Count natural numbers whose all permutation are greater than that number + * Input : n = 15. + * Output : 14 + * Explanation: + * 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, + * 13, 14, 15 are the numbers whose all + * permutation is greater than the number + * itself. So, output 14. + * + * Input : n = 100. + * Output : 54 + * + * An efficient solution is based on below observations. + * Observation 1: From 1 to 9, all number have this property. So, for n <= 9, + * output n. + * Observation 2: The number whose all permutation is greater than or equal to + * that number have all their digits in increasing order. + * The idea is to push all the number from 1 to 9. Now, pop the top element, say + * topel and try to make number whose digits are in increasing order and the + * first digit is topel. To make such numbers, the second digit can be from + * topel%10 to 9. If this number is less than n, increment the count and push + * the number in the stack, else ignore. + * + * Below is the implementation of this approach: + * + * + */ + +import java.util.*; + +public class SQ11 { + static int countNumber(int n) { + int result = 0; + Stack s = new Stack<>(); + + for (int i = 1; i <= 9; i++) { + if (i <= n) { + s.push(i); + result++; + } + + // take a number from stack and add + // a digit smaller than or equal to last digit + // of it. + while (!s.isEmpty()) { + int tp = s.pop(); + + for (int j = tp % 10; j <= 9; j++) { + int x = tp * 10 + j; + if (x <= n) { + s.push(x); + result++; + } + } + } + } + return result; + + } + + // Driven Code + public static void main(String[] args) { + int n = 15; + System.out.println(countNumber(n)); + } +} diff --git a/Stack/Probs/SQ12.class b/Stack/Probs/SQ12.class new file mode 100644 index 0000000000000000000000000000000000000000..8a496419629da723231b6a916f45d085fe72c868 GIT binary patch literal 1854 zcmaJ>-BTM?6#w0P?XoO{0%PJ)ggG?)i1^`A+~Y;em#B zBpT3$a|(Jj_>s`ifHx%drd;~u(y!pWWDjT*9F&~5Bz2(yZ{wnhOBycYN-GTxD;QDm zj)GAEF~vV6&@|@QW!JFXStDOD{ghG#LX+2K?xgMt_!kx^6B@E?%N^k{o|qK~j5*7u zKzPEk&8bRZ$t=wnOL=mF>$dYznR`5yO3c%C#x-*5lSa|IZ(6bJykW2QXWWuyuO_8Gbtsqj0?;x}rIa(rE$OZyGd(caCslNG zBC6vgIv7^fM#Z)Av_bbeuHm|lG2GDcF2;4dhnoV&4m_o7*IYGAI#TlXHFW8CAGdUz z#u)_@IwnD=^eLxnKXL_W9k($p&~n{z+_GCTij$_h<}8=PA>2`s(J_M$1bh;`fDDtO z2OiT)56zq_plnFY(DM(Ts#ud9Yx%n3B_quQ0a(Io^<6pVF~O_?*?Im=!9r#;zLk;5Q)mK5BTXx|g) zK0w&AH=K3TYoeO5aUUeTz}f%gcT{Wwul~OrPH{N2 z^P&6j3L-cTV(y((`GiOZ$>WRS8sjO(T}bY^XAs|#pbM^{D)S6f`DRE<(W^8nXGq&q z_&NqV`vQ-l1hx_I4@aMn?W-zk+=25rh5^PRz4^kUeCG1S)$E8<6bbTb>wEaK&k&gK zkHk8@Mr&_u7r`Bb=05R@?U%pz?$G=<7~-z}jD{U(BM0QgKr9m2MdKD)dL>cS+lIbx zWBcVVl-9Qp^gTIH8?L$PibcOdBuamcU!pMbI9SR^;}IvxrVMO7SP! z_HY40`~lUczJM;oN%0rKX+Ss5da&R3VDDCjI(N}D9Q8d$^HVgphIi1ijWEgRbK(si zWdUn-=wJzfd7c)aFg6_@vJ)0r1fv>-3f~Ky5TcQ}_3U@U$CQ=d1La4wX8p st = new Stack<>(); + int c; + + for (int i = 0; i < n; i++) { + st.push(i); + } + + while (st.size() > 1) { + int a = st.pop(); + int b = st.pop(); + + if (knows(a, b)) { + st.push(b); + } else { + st.push(a); + } + } + + // If there are only two people + // and there is no + // potential candidate + if (st.empty()) + return -1; + + c = st.pop(); + + for (int i = 0; i < n; i++) { + if (i != c && (knows(c, i) || !knows(i, c))) { + return -1; + } + } + return c; + + } + + // Driver Code + public static void main(String[] args) { + int n = 4; + int result = findCelebrity(n); + if (result == -1) { + System.out.println("No Celebrity"); + } else + System.out.println("Celebrity ID " + + result); + } +} diff --git a/Stack/Probs/SQ13.class b/Stack/Probs/SQ13.class new file mode 100644 index 0000000000000000000000000000000000000000..2f2d3ee4eeae9a4fcfedc0503320a13a145717d3 GIT binary patch literal 1107 zcmZuwT~iWK7=8{cEUb&-2Z$k=rnVqTW`07XkroA7L!(n&t+?VUECh?A_x*~lnr^(Q zi@HFkW}2@15&e)ZviB^^fHUsJIq!MTd7qE>oc;ap`%eIi*pe`SQ3=Bs6LDLDoiDmD z&Z7yQp5)OTJ}7($i-_<8Qxc+>c45Yi8172w$E<{Vm~-L2hTZ!T(!Or&W!006W-$1a%%OU$#)_&@h~>0%nZ#IJbyF`A z7valTL0m=x4`d|qP{u0OWIRGj#$%)ydfVF4hN%^_s*H6ki`bCy1W(Dcq9|d7nv|CD z49{f@;f9Eej4U=u1nntd{*ihvh{4-N+}b_V^5&IPvjGHK)Qp08V6~E(As(y6y0*2? z&8Nd1?pvbb1YfDw==@}7JDUXY&Vp8o81e^db&c2sLL{f6URy6!%u|c<4ULs@g<(Ls zwpgfW+7W|GH_UCWjG?=2E2~<-OLrJIkZFacMoz_gPLOXAOF&gatp1gR~0K%xHE*&cVJ?z!0F(X(fGd z@mr#pAN@n64w`F`25gBRu)jWskd4|d;Ap_PV^7)_1fLN6gj~cYG$4AFkMKr)LTmpF z^U(%eAK;?Nz0-^XA)i2z^b1`L$a@#?B+uY!7rhtQ+2xneXQH)P!dB2t@gNBaz(eBv zBrib!;wWy?UpInfidHd3Pj4IqmhM~s0n4b` Au>b%7 literal 0 HcmV?d00001 diff --git a/Stack/Probs/SQ13.java b/Stack/Probs/SQ13.java new file mode 100644 index 0000000..eccc176 --- /dev/null +++ b/Stack/Probs/SQ13.java @@ -0,0 +1,60 @@ +import java.util.Stack; + +/** + * Length of the longest valid substring + * + * Input : ((() + * Output : 2 + * Explanation : () + * + * Input: )()()) + * Output : 4 + * Explanation: ()() + * + * Input: ()(())))) + * Output: 6 + * Explanation: ()(()) + * + * + * + */ +public class SQ13 { + static int findMaxLen(String str) { + int n = str.length(); + Stack s = new Stack<>(); + s.push(-1); + int result = 0; + + for (int i = 0; i < n; i++) { + // If opening bracket, push index of it + if (str.charAt(i) == '(') + s.push(i); + else { + if (!s.isEmpty()) { + s.pop(); + } + if (!s.isEmpty()) { + result = Math.max(result, i - s.peek()); + } + + else { + s.push(i); + } + } + } + return result; + } + + // Driver code + public static void main(String[] args) { + String str = "((()()"; + + // Function call + System.out.println(findMaxLen(str)); + + str = "()(()))))"; + + // Function call + System.out.println(findMaxLen(str)); + } +} diff --git a/Stack/Probs/SQ14.class b/Stack/Probs/SQ14.class new file mode 100644 index 0000000000000000000000000000000000000000..b8e9b854ea4a842e2e624a1433ca700c2edd7c75 GIT binary patch literal 1993 zcmaJ>T~iuo7(ENf0$GC+#3rb1|LHN>`Yg%wwpT?Q6A-uFke zxy(!_H@QjDkdEnOdfngB=?~~+(w>*4iqR=EydTf!dCv2^`^Ve;*8ncT4B#B5{0QTs zjOhT}&Sl1r&u}S3lVkw1xGEHL!s=Q8J-9BeH$sq*^dTiK^D-8MW>H+e2*HJaLn-*t(I(*=nJjl;F?l zB~!HZU=7x1`z20*t5HsBd$NrGYbVu4B>qlw-wyMT?sumEz7Rk zHMP2|+1pmJ9`qvT!-|5h!E|d1?jf(>KGqcsVnD$+_*TJreCNXh2CoYmhZ|;5t8E$9 z_X^_JAknRyowO-XF|J?}8$J|RrGP5J#1xDQsQ1JY$2b8U`erwGv;zC)S|>3b^4wnC z)+%JoYEawf5T#p*+hoZmSDISkbQK{u;Vca6^((`Yg#L4*PQ0+C{-sXwuO}owz z?8|YwC7fwtIU1Q$RTX&*cBwCR+)FfA*6RzEs=e20>V4jKRimM0w?to$WcqKYID4I; zoWhfxnA##%Bt}Uqwkit8PBifm9;d#+`aM-mD+?#9T5UPW*b=SXkuY*dv~KQNWsPq_ zjG4pGqFS)6+MWzP9&g67$_N^RWgrWbp!w3AZoZ|<}%|BlhSD$zZ z+##M4KUTv$xoGF*nGcWa2qiQ0khu57UqXtzUceQ91$X`>JTK7olnO%Rdb$-j2oHMU z#~DiaAle}&7*>Snc?NI%7r6Ez15Nl2y#urWA_$_NJKs~=v&^VMbD3^kP52+;R8&NG z1YbNVpimrrhQPKEZv2WSEK4P st = new Stack(); + + void getMin() { + System.out.println("min is: " + min); + } + + void push(int val) { + // if stack is empty OR current element is less than + // min, update min.. + if (st.isEmpty() || val < min) { + min = val; + } + + st.push(val * demoVal + min); + + System.out.println("pushed: " + val); + + } + + int pop() { + // if stack is empty return -1; + if (st.isEmpty()) { + System.out.println("stack underflow"); + return -1; + } + + int val = st.pop(); + if (!st.isEmpty()) // if stack is empty, there would + // be no min value present, so + // make min as -1 + min = st.peek() % demoVal; + else + min = -1; + System.out.println("popped: " + val / demoVal); + return val / demoVal; // decode actual value from + // encoded value + } + + // Driver Code + public static void main(String[] args) { + SQ14 s = new SQ14(); + + int[] arr = { 1, 2, 3, 4 }; + + for (int i = 0; i < arr.length; i++) { + s.push(arr[i]); + s.getMin(); + } + System.out.println(); + for (int i = 0; i < arr.length; i++) { + s.pop(); + s.getMin(); + } + } +} diff --git a/Stack/Probs/SQ15.java b/Stack/Probs/SQ15.java new file mode 100644 index 0000000..4f01ddc --- /dev/null +++ b/Stack/Probs/SQ15.java @@ -0,0 +1,5 @@ +package Probs; + +public class SQ15 { + +} diff --git a/Stack/Probs/SQ16.java b/Stack/Probs/SQ16.java new file mode 100644 index 0000000..4564dce --- /dev/null +++ b/Stack/Probs/SQ16.java @@ -0,0 +1,113 @@ +/** + * Find maximum of minimum for every window size in a given array + * + * Input: arr[] = {10, 20, 30, 50, 10, 70, 30} + * Output: 70, 30, 20, 10, 10, 10, 10 + * The first element in the output indicates the maximum of minimums of all + * windows of size 1. + * Minimums of windows of size 1 are {10}, {20}, {30}, {50}, {10}, + * {70} and {30}. Maximum of these minimums is 70 + * The second element in the output indicates the maximum of minimums of all + * windows of size 2. + * Minimums of windows of size 2 are {10}, {20}, {30}, {10}, {10}, + * and {30}. Maximum of these minimums is 30 + * The third element in the output indicates the maximum of minimums of all + * windows of size 3. + * Minimums of windows of size 3 are {10}, {20}, {10}, {10} and {10}. + * Maximum of these minimums is 20 + * Similarly, other elements of output are computed. + */ +public class SQ16 { + static int arr[] = { 10, 20, 30, 50, 10, 70, 30 }; + + // method 1 + static void printMaxOfMin(int n) { + for (int k = 1; k <= n; k++) { + int maxOfMin = Integer.MIN_VALUE; + for (int i = 0; i <= n - k; i++) { + int min = arr[i]; + for (int j = 1; j < k; j++) { + if (arr[i + j] < min) { + min = arr[i + j]; + } + } + // Update maxOfMin if required + if (min > maxOfMin) + maxOfMin = min; + } + System.out.print(maxOfMin + " "); + } + } + + // method + // https://www.geeksforgeeks.org/find-the-maximum-of-minimums-for-every-window-size-in-a-given-array/ + static void printMaxOfMin2(int n) { + Stack s = new Stack<>(); + // Arrays to store previous and next smaller + int left[] = new int[n + 1]; + int right[] = new int[n + 1]; + + for (int i = 0; i < n; i++) { + left[i] = -1; + right[i] = n; + } + // Fill elements of left[] using logic discussed on + // https://www.geeksforgeeks.org/next-greater-element/ + for (int i = 0; i < n; i++) { + while (!s.isEmpty() && arr[s.peek()] >= arr[i]) { + s.pop(); + } + + if (!s.empty()) + left[i] = s.peek(); + + s.push(i); + } + + // Empty the stack as stack is + // going to be used for right[] + // Fill elements of right[] using same logic + for (int i = n - 1; i >= 0; i--) { + + while (!s.empty() && arr[s.peek()] >= arr[i]) + s.pop(); + + if (!s.empty()) + right[i] = s.peek(); + + s.push(i); + } + + // Create and initialize answer array + int ans[] = new int[n + 1]; + + for (int i = 0; i <= n; i++) + ans[i] = 0; + + // Fill answer array by comparing minimums of all + // lengths computed using left[] and right[] + for (int i = 0; i < n; i++) { + // length of the interval + int len = right[i] - left[i] - 1; + // arr[i] is a possible answer for this length + // 'len' interval, check if arr[i] is more than + // max for 'len' + ans[len] = Math.max(ans[len], arr[i]); + } + + // Some entries in ans[] may not be filled yet. Fill + // them by taking values from right side of ans[] + for (int i = n - 1; i >= 1; i--) + ans[i] = Math.max(ans[i], ans[i + 1]); + + // Print the result + for (int i = 1; i <= n; i++) + System.out.print(ans[i] + " "); + + } + + // Driver method + public static void main(String[] args) { + printMaxOfMin(arr.length); + } +} diff --git a/Stack/Probs/SQ17.java b/Stack/Probs/SQ17.java new file mode 100644 index 0000000..e6d6a81 --- /dev/null +++ b/Stack/Probs/SQ17.java @@ -0,0 +1,53 @@ + +/** + * Queue based approach for first non-repeating character in a stream + * + * + * Given a stream of characters and we have to find first non repeating + * character each time a character is inserted to the stream. + * + * Input : a a b c + * Output : a -1 b b + * + * Input : a a c + * Output : a -1 c + * + * + * + * + */ +import java.util.*; + +public class SQ17 { + final static int MAX_CHAR = 26; + + static void firstNonRepeating(String str) { + int[] charCount = new int[MAX_CHAR]; + Queue q = new LinkedList(); + for (int i = 0; i < str.length(); i++) { + char ch = str.charAt(i); + + q.add(ch); + + charCount[ch - 'a']++; + while (!q.isEmpty()) { + if (charCount[q.peek() - 'a'] > 1) { + q.remove(); + } else { + System.out.print(q.peek() + " "); + break; + } + } + if (q.isEmpty()) + System.out.print(-1 + " "); + } + System.out.println(); + + } + + // Driver function + public static void main(String[] args) { + String str = "aabc"; + firstNonRepeating(str); + } +} diff --git a/Stack/Probs/SQ18.class b/Stack/Probs/SQ18.class new file mode 100644 index 0000000000000000000000000000000000000000..2f339b222cd338858e1c8c1b0fc1d54aac2399b2 GIT binary patch literal 2024 zcmaJ?TUQ%Z6#h;KOfpQ%{Zgn{6==AWlu~VN0But$(E!CD*rL`UIlw?NlV)bH)IXv= z^~Kd^T`iS%Etk*!5PyYB{Z3{eX=#1PVV`~d_P6&L{`}|p?*OjgdmU#nrQx!U2&Urb z#rqmQ(9sxNt|-k_9jEZ2(p_st3e)PC(J-sjA1U?6N^@OFH%IQ~X)f7zG56llxtn0sc@_pD;_ro8XVlt4UZZP}*h zS7;x8)jl04il)7l%-EjXl9kjfgS2ha-Ofo*prbBiK2Xx0IH`S8Dm{HYJwJCZm$^G9 zATk0?)0S;{vjWjXW@MFr(oTWcTC$cc7yZ(PtgM(DMQR!=a#L0WPUSo^zq??TL%mk8 z+;Y*}7idU~tZK+HN6EBof$qe5T|+sqV%b|MRYT7?ekCt&St@Tlw>)`uLNR4v7#9RO zYpfB(t}J9N*E8@I21sem7PfET9lUE`5JLu5@P&a@tZDetz#ZH*u#T^eg6df{@U^mj zgEa&9@T~z;NgK!;C_rl1G_Zwj1C|PJz2P{X>s8G1g7mhXg4@!Bofviv6j9P(8*or& z)2a{E!g&Lu>KIqev{nIEYcFl=$UJA*Uh5&_$%^SYWL4WUi@sdiRIFu2>S#OK1A$oH zu{{#&3Uq}NugjYnxyz~5Qdbv_s9ftIN#dOS+xJxn1_Er@Z zu14U_BxT>-enVA`v%xGBRN!$l-AAdbtAEsFxX6q00jm=b@z$}E+jl)#qQUWL?g|*N zoaAk8jmO=QW{C-+Hluai2Pun)a{@gjb62JvJ8ybxmbXpG^-S9%N5ikt0rcUupVyhc&or{ND)-)&^|Zd(N&*22KH{TV|f)-Pge9(Uf(ZU7wp`WNcej z(nZsCC4v4>4>ZgXY}&kO7mCsy3<6Up!PjYC3S8MQ%h$NqKgV$3^*a!zNSnoCj>Al8 zcqlM*qQBQ+6Bzh^KfcmlexQK{exCW1A@DYD5uD?XFZlTW9@^DorY*`JUlT0}O7qo7 z;N0jlh|w2_+^x+!%F+*Z9gt$slHb}}Cy`qTBG!ra8 zCL!c?W{J>}P?ZkRE|48NM2EnS==l|$l)D6;vwIw%=kdRP)#|oaDIJ1NT02O=d7@D@ z;)whWUBkp#ib-4y3l&1f$6uiLj`j>^vSZN$^o=#Dqe&grtEQxwIu6iZV?SteoEa~$ u(FqnzvfYbpagx)%#Ntydewj5U2_Ztw9{=jB?co7@(lXC`jQ0$GpZ*8u9oYu} literal 0 HcmV?d00001 diff --git a/Stack/Probs/SQ18.java b/Stack/Probs/SQ18.java new file mode 100644 index 0000000..7a71c92 --- /dev/null +++ b/Stack/Probs/SQ18.java @@ -0,0 +1,119 @@ + +import java.util.Deque; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Iterator; + +public class SQ18 { + // store keys of cache + private Deque doublyQueue; + + // store references of key in cache + private HashSet hashSet; + + private final int CACHE_SIZE; + + SQ18(int capacity) { + doublyQueue = new LinkedList<>(); + hashSet = new HashSet<>(); + CACHE_SIZE = capacity; + } + + public void refer(int page) { + if (!hashSet.contains(page)) { + if (doublyQueue.size() == CACHE_SIZE) { + int last = doublyQueue.removeLast(); + hashSet.remove(last); + } + } else { + hashSet.remove(page); + } + doublyQueue.push(page); + hashSet.add(page); + } + + // display contents of cache + public void display() { + Iterator itr = doublyQueue.iterator(); + while (itr.hasNext()) { + System.out.print(itr.next() + " "); + } + } + + + /** + * method 2 + * + * Set cache; + * int capacity; + * + * + * public LRUCache(int capacity) + * { + * this.cache = new LinkedHashSet(capacity); + * this.capacity = capacity; + * } + * + * // This function returns false if key is not + * // present in cache. Else it moves the key to + * // front by first removing it and then adding + * // it, and returns true. + * + * + * public boolean get(int key) + * { + * if (!cache.contains(key)) + * return false; + * cache.remove(key); + * cache.add(key); + * return true; + * } + * + * + * public void refer(int key) + * { + * if (get(key) == false) + * put(key); + * } + * + * + * // displays contents of cache in Reverse Order + * public void display() + * { + * LinkedList list = new LinkedList<>(cache); + * + * // The descendingIterator() method of java.util.LinkedList + * // class is used to return an iterator over the elements + * // in this LinkedList in reverse sequential order + * Iterator itr = list.descendingIterator(); + * + * while (itr.hasNext()) + * System.out.print(itr.next() + " "); + * } + * + * + * public void put(int key) + * { + * + * if (cache.size() == capacity) { + * int firstKey = cache.iterator().next(); + * cache.remove(firstKey); + * } + * + * cache.add(key); + * } + * + * @param args + */ + + public static void main(String[] args) { + SQ18 cache = new SQ18(4); + cache.refer(1); + cache.refer(2); + cache.refer(3); + cache.refer(1); + cache.refer(4); + cache.refer(5); + cache.display(); + } +} diff --git a/Stack/Probs/SQ19$petrolPump.class b/Stack/Probs/SQ19$petrolPump.class new file mode 100644 index 0000000000000000000000000000000000000000..08dca61956402936682aa0f62efe62f4655ab3ee GIT binary patch literal 356 zcmYk1OH0E*6ot>ENt4uQVtqf*7F@JhSj2@0;-(-5q$-u}lXQ@jG%0!bzg!f-g+IU_ zC7!7p7jy31!=3NU{r>s<0&s=H77T3K(9u@1Wn$aJoIld=l4Skk{q zvZT5dFnU4Ip9tu~d`jPaNHRI9=aDR4!YHNF8s~Kp%ezE1_W1eY`g|6?g`|ySS>5Ml zWn$lfjROZwm<}wMsykSiAxM^U)z@mWJw*8LR-0ij60@1ST+MQC<>UQm} zfWGdyj$af|GTDa$YRPNZ0^=3OwRd{0eY>+~?Kf$Ov^$RL?|HqBz~#)7O7)wiwe$!# zU(S{VE>(T2ez0w|he75^(6WJBL~mJ+JBWX7y|5OWmiu(E>J#~CKKszXk^ws2CgUm- z)$L6uNG)?M$N+({9lPsq+mcu}igCoE_!KKqtYU?%|3gYT+=*fW9~k&7iZ$Go0N!-f zYxaD{Ba_&D&-1%}$7*le{xh%99oLZ$V?Bxjic#Fd21!d)x{ersz5m><`vURvZ4j7v zQW<#;Yoj%=Io{%~Y$MIK)jESY@T4Ato(c%|Gu&{xzU9{0e=SokOMy<&s2+BGn<$Fc zBbme??b#H06QAQg)uS*Sf4VR&1SVV7fnD<4y5&D|{AWDL96tX-B2&&@MBWHwY_ea8 z%=vdITuC-;Qy@Jm-Em)d2li0iLAp(=?t7g>16!=K;&}%>{>Sf5Lk@!mVr*G%qiJ{3 z1JC^V%%?180{0Hv_66>zg&9bgKV9w+qGUCjRmZpU2B^UGa|K<*P2k%9`(cI?8s%Vu zJeh)45im#~vLas`qMhy8{JnFwrzG9Y8z+*We zJ!YPgLAqsO4W!-NnbGIy0lTs|q{C1G?r zY$*k$sI02Ws+Q2EUSffK5?Vkg*aAkfmT{6Uq!MaPdVi~lqyFCsHC6ioM)C-1Xhby! zlelZdzY7C-c6c3W{>m(hBzX_Z*uV~+()FmE1LL~WyxOfdy ziacm;oLt!nwz0yt?Vya^fY}^EeUeoST$SV?3{3SY{fQw&gMlQ&QvujDe8gRTEEVtZ a6lVgJ8eC%Qzra^i=L*{Z-UPK1nEw|BTwwSB literal 0 HcmV?d00001 diff --git a/Stack/Probs/SQ19.java b/Stack/Probs/SQ19.java new file mode 100644 index 0000000..23c2197 --- /dev/null +++ b/Stack/Probs/SQ19.java @@ -0,0 +1,82 @@ + +/** + * Find the first circular tour that visits all petrol pumps + * + * + * Suppose there is a circle. There are n petrol pumps on that circle. You are + * given two sets of data. + * + * The amount of petrol that every petrol pump has. + * Distance from that petrol pump to the next petrol pump. + * Calculate the first point from where a truck will be able to complete the + * circle (The truck will stop at each petrol pump and it has infinite + * capacity). Expected time complexity is O(n). Assume for 1-litre petrol, the + * truck can go 1 unit of distance. + * For example, let there be 4 petrol pumps with amount of petrol and distance + * to next petrol pump value pairs as {4, 6}, {6, 5}, {7, 3} and {4, 5}. The + * first point from where the truck can make a circular tour is 2nd petrol pump. + * Output should be “start = 1” (index of 2nd petrol pump). + * + * + * + */ +public class SQ19 { + // A petrol pump has petrol and distance to next petrol pump + static class petrolPump { + int petrol; + int distance; + + // constructor + public petrolPump(int petrol, int distance) { + this.petrol = petrol; + this.distance = distance; + } + } + + // method 1 + static int printTour(petrolPump arr[], int n) { + int start = 0; + int end = 1; + int curr_petrol = arr[start].petrol - arr[start].distance; + while (end != start || curr_petrol < 0) { + if (curr_petrol < 0 && start != end) { + curr_petrol -= arr[start].petrol - arr[start].distance; + start = (start + 1) % n; + if (start == 0) + return -1; + } + curr_petrol += arr[end].petrol - arr[end].distance; + end = (end + 1) % n; + } + return start; + + } + + // method 2 + static int printTour2(petrolPump p[], int n) { + int start = 0, deficit = 0; + int capacity = 0; + for (int i = 0; i < n; i++) { + capacity += p[i].petrol - p[i].distance; + if (capacity < 0) { + start = start + 1; + deficit += capacity; + capacity = 0; + } + } + return (capacity + deficit >= 0) ? start : -1; + } + + public static void main(String[] args) { + + petrolPump[] arr = { new petrolPump(6, 4), + new petrolPump(3, 6), + new petrolPump(7, 3) }; + + int start = printTour(arr, arr.length); + + System.out.println(start == -1 ? "No Solution" : "Start = " + start); + + } + +} diff --git a/String/1_index.txt b/String/1_index.txt index 5661ea3..d3822da 100644 --- a/String/1_index.txt +++ b/String/1_index.txt @@ -4,4 +4,21 @@ 4.remove duplicates from string 5.move all x to end 6.print all subsequence;] -7.pring all permutations \ No newline at end of file +7.pring all permutations +8.Check whether two strings are anagram of each other +9.valid parenthesis +10.print all duplicates +11.print subsequence +12.minimum edit distance +13.longest palindromic subsequence +14.wildcard string matching +15.word wrap +16. Longest Substring Without Repeating Characters +17.longest palindromic substring +18.palindrominc substring count +19.Count All Palindromic Subsequence in a given String +20. +21.group anagram +22.longest common prefix +23.longest common prefix sufix (*) +24.find the smallest window in a string containing all characters of another string (*) \ No newline at end of file diff --git a/String/prob_str12.java b/String/prob_str12.java index 504ceff..8737857 100644 --- a/String/prob_str12.java +++ b/String/prob_str12.java @@ -1,3 +1,4 @@ +//minimum edit distance public class prob_str12 { public int minEditDistance(String s1, String s2) { int t[][] = new int[s1.length() + 1][s2.length() + 1]; diff --git a/String/prob_str13.java b/String/prob_str13.java index baf1397..b2cf147 100644 --- a/String/prob_str13.java +++ b/String/prob_str13.java @@ -12,7 +12,7 @@ public int longestPaliSubse(String str) { if (l == 2 && str.charAt(i) == str.charAt(j)) { temp[i][j] = 2; } else if (str.charAt(i) == str.charAt(j)) { - temp[i][j] = 2 + t[i + 1][j][j - 1][i]; + temp[i][j] = 2 + t[i + 1][j - 1]; } else { temp[i][j] = Math.max(temp[i + 1][j], temp[i][j - 1]); } diff --git a/String/prob_str14.java b/String/prob_str14.java index 12ea946..c55b782 100644 --- a/String/prob_str14.java +++ b/String/prob_str14.java @@ -4,7 +4,6 @@ public class prob_str14 { public boolean isMatch(String s, String p) { char[] str = s.toCharArray(); char[] pattern = p.toCharArray(); - int writeIndex = 0; boolean isFirst = true; for (int i = 0; i < pattern.length; i++) { diff --git a/String/prob_str17.java b/String/prob_str17.java index 10a96d9..49505d0 100644 --- a/String/prob_str17.java +++ b/String/prob_str17.java @@ -1,3 +1,4 @@ +//longest palindromic substring public class prob_str17 { static int longestPalindromSubString(String str) { int n = str.length(); diff --git a/String/prob_str18.class b/String/prob_str18.class index 9ce45c6f8eb4d5a0ad2f22996afa2fe4def224f4..35e48731002b91da3ea37eb9ab0b6005b9425e19 100644 GIT binary patch delta 32 ncmZo;Z)KklCn{Nxn3I{8Qk0*YnH*f2R9sS&nU}t?M2Hyxy#ouw delta 33 ocmZo=Z)2YjCni;pn3I{8Qk0*YnH*f2RGeB^nwp%tu~>*10LdQ=7ytkO diff --git a/String/prob_str18.java b/String/prob_str18.java index d107550..0ca97e3 100644 --- a/String/prob_str18.java +++ b/String/prob_str18.java @@ -1,3 +1,5 @@ +//palindrominc substring count + public class prob_str18 { public static int palindromicSubstringCount(String str) { int n = str.length(); @@ -11,13 +13,17 @@ public static int palindromicSubstringCount(String str) { count++; } - for (int l = 2; l <= n; l++) { + for (int i = 0; i < n - 1; i++) { + if (str.charAt(i) == str.charAt(i + 1)) { + count++; + t[i][i + 1] = true; + } + } + + for (int l = 3; l <= n; l++) { for (int i = 0; i <= n - l; i++) { int j = i + l - 1; - if (l == 2 && str.charAt(i) == str.charAt(j)) { - t[i][j] = true; - count++; - } else if (t[i + 1][j - 1] && str.charAt(i) == str.charAt(j)) { + if (t[i + 1][j - 1] && str.charAt(i) == str.charAt(j)) { t[i][j] = true; count++; } @@ -29,7 +35,7 @@ public static int palindromicSubstringCount(String str) { public static void main(String[] args) { String Str = "abbaeae"; - System.out.println(palindromicSubsequeceCount(Str)); + System.out.println(palindromicSubstringCount(Str)); } } diff --git a/String/prob_str20.class b/String/prob_str20.class index e9fef06f98758dd6ce01e7ffbf35a4b0f2e5f1a1..4c8b860fdc1eb59dbb3248a309f426470db6d664 100644 GIT binary patch delta 91 zcmWN|OA0_h0D$4&$S9?hn(=-l<&lM*3%CIrC$MrEwDxQ??@Q_8H;OF rSZHhl93os2LQ)zsCURy97D_fM_TLWb^A)RZG3ox<<1t{M0D=AhNUjRC delta 91 zcmX@dc8+a>6cZ!kWND^phAa%MK*-L(#=ynE!N3b7B^kIGG#GdoEPy;$20n%m27ZPp o20?}lpj;k<@Z?8Kq2l5U%nTAheUc0U4AKmY3}Orn3``8-01ciAaR2}S diff --git a/String/prob_str22.java b/String/prob_str22.java index 5234461..4d590ef 100644 --- a/String/prob_str22.java +++ b/String/prob_str22.java @@ -16,6 +16,8 @@ public static String longestCommonPrefix(String[] strs) { return prefix; } + + public static void main(String[] args) { String[] strs = { "flower", "flow", "flight" }; System.out.println(longestCommonPrefix(strs)); diff --git a/String/prob_str24.java b/String/prob_str24.java index 86a2a28..cd41ca8 100644 --- a/String/prob_str24.java +++ b/String/prob_str24.java @@ -39,7 +39,6 @@ static String Minimum_Window(char[] s, char[] t) { m[s[i]]++; if (m[s[i]] > 0) count++; - i++; } } diff --git a/String/prob_str25.java b/String/prob_str25.java new file mode 100644 index 0000000..aba0976 --- /dev/null +++ b/String/prob_str25.java @@ -0,0 +1,48 @@ +public class prob_str25 { + private int prime = 101; + + private long recalculateHash(char[] str, int oldIndex, int newIndex, long oldHash, int patternLen) { + long newHash = oldHash - str[oldIndex]; + newHash = newHash / prime; + newHash += str[newIndex] * Math.pow(prime, patternLen - 1); + return newHash; + + } + + private long createHash(char[] str, int end) { + long hash = 0; + for (int i = 0; i <= end; i++) { + hash += str[i] * Math.pow(prime, i); + } + return hash; + } + + private boolean checkEqual(char str1[], int start1, int end1, char str2[], int start2, int end2) { + if (end1 - start1 != end2 - start2) { + return false; + } + while (start1 <= end1 && start2 <= end2) { + if (str1[start1] != str2[start2]) { + return false; + } + start1++; + start2++; + } + return true; + } + + public int patternSearch(char[] text, char[] pattern) { + int m = pattern.length; + int n = text.length; + long patternHash = createHash(pattern, m - 1); + long textHash = createHash(text, m - 1); + for (int i = 1; i <= n - m + 1; i++) { + if (patternHash == textHash && checkEqual(text, i - 1, i + m - 2, pattern, 0, m - 1)) { + return i - 1; + } + if (i < n - m + 1) { + textHash = recalculateHash(text, i - 1, i + m - 1, textHash, m); + } + } + } +} diff --git a/String/prob_str26.java b/String/prob_str26.java new file mode 100644 index 0000000..815069e --- /dev/null +++ b/String/prob_str26.java @@ -0,0 +1,141 @@ +/** + * Boyer Moore Algorithm for Pattern Searching + * Pattern searching is an important problem in computer science. When we do + * search for a string in a notepad/word file, browser, or database, pattern + * searching algorithms are used to show the search results. A typical problem + * statement would be- + * Given a text txt[0..n-1] and a pattern pat[0..m-1] where n is the length of + * the text and m is the length of the pattern, write a function search(char + * pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may + * assume that n > m. + * + * + * Input: txt[] = "THIS IS A TEST TEXT" + * pat[] = "TEST" + * Output: Pattern found at index 10 + * + * Input: txt[] = "AABAACAADAABAABA" + * pat[] = "AABA" + * Output: Pattern found at index 0 + * Pattern found at index 9 + * Pattern found at index 12 + * + * + * In this post, we will discuss the Boyer Moore pattern searching algorithm. + * Like KMP and Finite Automata algorithms, Boyer Moore algorithm also + * preprocesses the pattern. + * Boyer Moore is a combination of the following two approaches. + * 1) Bad Character Heuristic + * 2) Good Suffix Heuristic + * Both of the above heuristics can also be used independently to search a + * pattern in a text. Let us first understand how two independent approaches + * work together in the Boyer Moore algorithm. If we take a look at the Naive + * algorithm, it slides the pattern over the text one by one. KMP algorithm does + * preprocessing over the pattern so that the pattern can be shifted by more + * than one. The Boyer Moore algorithm does preprocessing for the same reason. + * It processes the pattern and creates different arrays for each of the two + * heuristics. At every step, it slides the pattern by the max of the slides + * suggested by each of the two heuristics. + * + * + * https://www.geeksforgeeks.org/boyer-moore-algorithm-for-pattern-searching/ + * + * + * Bad Character Heuristic + * + * The idea of bad character heuristic is simple. The character of the text + * which doesn’t match with the current character of the pattern is called the + * Bad Character. Upon mismatch, we shift the pattern until – + * 1) The mismatch becomes a match + * 2) Pattern P moves past the mismatched character. + * Case 1 – Mismatch become match + * Case 2 – Pattern move past the mismatch character + * + */ + +public class prob_str26 { + static int NO_OF_CHARS = 256; + + static int max(int a, int b) { + return (a > b) ? a : b; + } + + static void badCharHeuristic(char[] str, int size, int badchar[]) { + for (int i = 0; i < NO_OF_CHARS; i++) { + badchar[i] = -1; + } + + // Fill the actual value of last occurrence + // of a character (indices of table are ascii and values are index + for (int i = 0; i < size; i++) { + badchar[(int) str[i]] = i; + } + + } + + static void search(char txt[], char pat[]) { + int m = pat.length; + int n = txt.length; + + int badchar[] = new int[NO_OF_CHARS]; + /* + * Fill the bad character array by calling + * the preprocessing function badCharHeuristic() + * for given pattern + */ + + badCharHeuristic(pat, m, badchar); + int s = 0; // s is shift of the pattern with + // respect to text + + while (s <= (n - m)) { + int j = m - 1; + + while (j > 0 && pat[j] == txt[s + j]) { + j--; + } + /* + * If the pattern is present at current + * shift, then index j will become -1 after + * the above loop + */ + + if (j < 0) { + System.out.println("Patterns occur at shift = " + s); + + /* + * Shift the pattern so that the next + * character in text aligns with the last + * occurrence of it in pattern. + * The condition s+m < n is necessary for + * the case when pattern occurs at the end + * of text + */ + // txt[s+m] is character after the pattern in text + s += (s + m < n) ? m - badchar[txt[s + m]] : 1; + } else { + /* + * Shift the pattern so that the bad character + * in text aligns with the last occurrence of + * it in pattern. The max function is used to + * make sure that we get a positive shift. + * We may get a negative shift if the last + * occurrence of bad character in pattern + * is on the right side of the current + * character. + */ + s += max(1, j - badchar[txt[s + j]]); + } + } + + } + + /* Driver program to test above function */ + public static void main(String[] args) { + + char txt[] = "ABAAABCD".toCharArray(); + char pat[] = "ABC".toCharArray(); + search(txt, pat); + } + +} diff --git a/String/prob_str7.class b/String/prob_str7.class index 0869d54874942f2994082e22b6e6b6e09627b3c4..d56eb0a548728f85ec2f1e2b134ff94132fe7171 100644 GIT binary patch delta 93 zcmX@gb%bk!7mMtC1{MZZ1_lN{t!)fUvlzHHF)(XyV_?|`=1$IF@zrNx-~+1QXJBU# qW8h>EXW(W~WZ+>?XW(V92Fkbt`MwMS45C0YxEWaZ*(X0?Ndy2bBo0*o delta 94 zcmX@Yb(Cv^7mM5i1{MZZ1_lOyt!)fUvlv)5Y6EGu1q|Gq7?`!UO-^U=)n{ekU|?qu s0FvSioD32S+zd(#JPaBPybLxBd<-5yz8_Fl6le%H0}BWLu0+mR#U7tVLC+U zlBOqSU)+Hz8+&I=kO@(y*vurSgg#=x6BAu{RS)B&Mf}P#6ZV1tOA@T)crDW#Xav=Pxz94XK#FjFQsf-C6;+O!euCft8l&_=hlnOpMb zDtb51IULUO@}4uN%&SYL)y1PHzptM_=71KDw(G9$hg>pJVyJ{??Nv=f3D}dw(fqbM_v`5*9g~gm{&X>1 ci4D@?SbSBJ32ok#FlEV%Pqo?bZlk3C55YGX`Tzg` diff --git a/Tree/TreeProblems/tree_prob10.java b/Tree/TreeProblems/tree_prob10.java index 6fde864..0202dfa 100644 --- a/Tree/TreeProblems/tree_prob10.java +++ b/Tree/TreeProblems/tree_prob10.java @@ -1,3 +1,19 @@ +/** + * Find distance between two nodes of a Binary Tree + * + * Find the distance between two keys in a binary tree, no parent pointers are + * given. The distance between two nodes is the minimum number of edges to be + * traversed to reach one node from another. + * + * + * Dist(n1, n2) = Dist(root, n1) + Dist(root, n2) - 2*Dist(root, lca) + * 'n1' and 'n2' are the two given keys + * 'root' is root of given Binary Tree. + * 'lca' is lowest common ancestor of n1 and n2 + * Dist(n1, n2) is the distance between n1 and n2. + * + */ + public class tree_prob10 { class Node { int data; @@ -10,7 +26,6 @@ class Node { this.right = null; } } - public Node lca(Node root, int n1, int n2) { if (root == null) { return null; diff --git a/Tree/TreeProblems/tree_prob13.java b/Tree/TreeProblems/tree_prob13.java index c1fdb94..3453bd1 100644 --- a/Tree/TreeProblems/tree_prob13.java +++ b/Tree/TreeProblems/tree_prob13.java @@ -1,3 +1,5 @@ +//find maxsum path in binary tree + public class tree_prob13 { class Node { int data; @@ -13,7 +15,6 @@ class Node { class Res { public int val; - } int findMaxUtil(Node root, Res res) { diff --git a/Tree/TreeProblems/tree_prob15.java b/Tree/TreeProblems/tree_prob15.java index 12d794c..cf8639e 100644 --- a/Tree/TreeProblems/tree_prob15.java +++ b/Tree/TreeProblems/tree_prob15.java @@ -1,10 +1,9 @@ //inorder predecessor and succesor -// predecessor - largest in left +//predecessor - largest in left //successor - smallest in right public class tree_prob15 { - class Node { int data; Node left; @@ -12,7 +11,6 @@ class Node { Node() { }; - Node(int data) { this.data = data; this.left = null; @@ -49,7 +47,6 @@ public void findPreSuc(Node root, int key) { suc = root; findPreSuc(root.left, key); } - else { pre = root; findPreSuc(root.right, key); diff --git a/Tree/TreeProblems/tree_prob17.java b/Tree/TreeProblems/tree_prob17.java index e5749a8..16a2055 100644 --- a/Tree/TreeProblems/tree_prob17.java +++ b/Tree/TreeProblems/tree_prob17.java @@ -1,3 +1,4 @@ +//create bst from preorder public class tree_prob17 { class Node { int data; diff --git a/Tree/TreeProblems/tree_prob18.java b/Tree/TreeProblems/tree_prob18.java index d06f764..c6ef453 100644 --- a/Tree/TreeProblems/tree_prob18.java +++ b/Tree/TreeProblems/tree_prob18.java @@ -1,3 +1,5 @@ +//sorted array to bst + public class tree_prob18 { class Node { int data; diff --git a/Tree/TreeProblems/tree_prob19.java b/Tree/TreeProblems/tree_prob19.java index 8268073..e72d256 100644 --- a/Tree/TreeProblems/tree_prob19.java +++ b/Tree/TreeProblems/tree_prob19.java @@ -1,5 +1,5 @@ import java.util.Stack; - +//zigzag traversal public class tree_prob19 { class Node { int data; diff --git a/Tree/TreeProblems/tree_prob3.java b/Tree/TreeProblems/tree_prob3.java index b50ad13..9fa0619 100644 --- a/Tree/TreeProblems/tree_prob3.java +++ b/Tree/TreeProblems/tree_prob3.java @@ -17,7 +17,7 @@ class Node { Node buildTree(int inorder[], int postOrder[], int start, int end) { if (start > end) { - return nulll; + return null; } Node node = Node(postOrder[postIndex--]); diff --git a/Tree/TreeProblems/tree_prob7.java b/Tree/TreeProblems/tree_prob7.java index ca55b0d..c2d2376 100644 --- a/Tree/TreeProblems/tree_prob7.java +++ b/Tree/TreeProblems/tree_prob7.java @@ -1,11 +1,13 @@ import java.util.*; +//left view printing +//left view means , print the left element of each level + public class tree_prob7 { class Node { int data; Node left; Node right; - Node(int data) { this.data = data; this.left = null; @@ -14,6 +16,7 @@ class Node { } + public void leftview(Node root) { if (root == null) { return; diff --git a/Tree/TreeProblems/tree_prob8.java b/Tree/TreeProblems/tree_prob8.java index db595b4..2101b4f 100644 --- a/Tree/TreeProblems/tree_prob8.java +++ b/Tree/TreeProblems/tree_prob8.java @@ -1,3 +1,5 @@ + +//replace data of node equal to sum of leftsubtree and right subtree public class tree_prob8 { class Node { @@ -16,7 +18,6 @@ public void sumReplace(Node root) { if (root == null) { return; } - sumReplace(root.left); sumReplace(root.right); if (root.left != null) { diff --git a/Tree/TreeProblems/tree_prob9.java b/Tree/TreeProblems/tree_prob9.java index 47b9ddf..ed4c4ae 100644 --- a/Tree/TreeProblems/tree_prob9.java +++ b/Tree/TreeProblems/tree_prob9.java @@ -1,3 +1,6 @@ +//check if the tree is height balanced or not +//a tree is height balance if the at each node difference bet height of leftsubtree +//and right subtree is less than or equal to 1 class Height { int height = 0; diff --git a/getTranquilApys.js b/getTranquilApys.js new file mode 100644 index 0000000..647041d --- /dev/null +++ b/getTranquilApys.js @@ -0,0 +1,132 @@ +const BigNumber = require('bignumber.js'); +const { oneWeb3: web3 } = require('../../../utils/web3'); + +const fetchPrice = require('../../../utils/fetchPrice'); +const { compound } = require('../../../utils/compound'); +const Comptroller = require('../../../abis/harmony/Comptroller.json'); +const TqToken = require('../../../abis/TqToken.json'); +const pools = require('../../../data/one/tranquilLpPools.json'); +const getBlockTime = require('../../../utils/getBlockTime'); +const { BASE_HPY, ONE_CHAIN_ID: chainId } = require('../../../constants'); + +const COMPTROLLER = '0x6a82A17B48EF6be278BBC56138F35d04594587E3'; + +const getTranquilApys = async () => { + + let apys = {}; + let promises = []; + pools.forEach(pool => promises.push(getPoolApy(pool))); + const values = await Promise.all(promises); + for (let item of values) + { + apys = { ...apys, ...item }; + } + return apys; +}; + +const getPoolApy = async pool => { + const secondsPerBlock = await Promise.all([getBlockTime(chainId)]); + const BLOCKS_PER_YEAR = 31536000 / secondsPerBlock; + const [{ supplyBase, supplyVxs }, { borrowBase, borrowVxs }] = await Promise.all([ + getSupplyApys(pool, BLOCKS_PER_YEAR), + getBorrowApys(pool, BLOCKS_PER_YEAR), + ]); + + const { leveragedSupplyBase, leveragedBorrowBase, leveragedSupplyVxs, leveragedBorrowVxs } = + getLeveragedApys( + supplyBase, + borrowBase, + supplyVxs, + borrowVxs, + pool.borrowDepth, + pool.borrowPercent + ); + + const totalVxs = leveragedSupplyVxs.plus(leveragedBorrowVxs); + const compoundedVxs = compound(totalVxs, BASE_HPY, 1, 0.955); + const apy = leveragedSupplyBase.minus(leveragedBorrowBase).plus(compoundedVxs).toNumber(); + + return { [pool.name]: apy }; +}; + +const getSupplyApys = async (pool, BLOCKS_PER_YEAR) => { + const tqTokenContract = new web3.eth.Contract(TqToken, pool.tqToken); + const comptrollerContract = new web3.eth.Contract(Comptroller, COMPTROLLER); + let [tranqPrice, tokenPrice, supplyRate, compRate, totalSupply, exchangeRateStored] = + await Promise.all([ + fetchPrice({ oracle: 'tokens', id: 'TRANQ' }), + fetchPrice({ oracle: pool.oracle, id: pool.oracleId }), + tqTokenContract.methods.supplyRatePerTimestamp().call(), + comptrollerContract.methods.rewardSpeeds(0, pool.tqToken).call(), + tqTokenContract.methods.totalSupply().call(), + tqTokenContract.methods.exchangeRateStored().call(), + ]); + + supplyRate = new BigNumber(supplyRate); + compRate = new BigNumber(compRate); + totalSupply = new BigNumber(totalSupply); + exchangeRateStored = new BigNumber(exchangeRateStored); + const supplyApyPerYear = supplyRate.times(BLOCKS_PER_YEAR).div('1e18'); + const compPerYear = compRate.times(BLOCKS_PER_YEAR); + const compPerYearInUsd = compPerYear.div('1e18').times(tranqPrice); + const totalSupplied = totalSupply.times(exchangeRateStored).div('1e18'); + const totalSuppliedInUsd = totalSupplied.div(pool.decimals).times(tokenPrice); + return { + supplyBase: supplyApyPerYear, + supplyVxs: compPerYearInUsd.div(totalSuppliedInUsd), + }; +}; + +const getBorrowApys = async (pool, BLOCKS_PER_YEAR) => { + const comptrollerContract = new web3.eth.Contract(Comptroller, COMPTROLLER); + const tqTokenContract = new web3.eth.Contract(TqToken, pool.tqToken); + + let [tranqPrice, tokenPrice, borrowRate, compRate, totalBorrows] = await Promise.all([ + fetchPrice({ oracle: 'tokens', id: 'TRANQ' }), + fetchPrice({ oracle: pool.oracle, id: pool.oracleId }), + tqTokenContract.methods.borrowRatePerTimestamp().call(), + comptrollerContract.methods.rewardSpeeds(0, pool.tqToken).call(), + tqTokenContract.methods.totalBorrows().call(), + ]); + borrowRate = new BigNumber(borrowRate); + compRate = new BigNumber(compRate); + totalBorrows = new BigNumber(totalBorrows); + const borrowApyPerYear = borrowRate.times(BLOCKS_PER_YEAR).div('1e18'); + const compPerYear = compRate.times(BLOCKS_PER_YEAR); + const compPerYearInUsd = compPerYear.div('1e18').times(tranqPrice); + const totalBorrowsInUsd = totalBorrows.div(pool.decimals).times(tokenPrice); + return { + borrowBase: borrowApyPerYear, + borrowVxs: compPerYearInUsd.div(totalBorrowsInUsd), + }; +}; + +const getLeveragedApys = (supplyBase, borrowBase, supplyVxs, borrowVxs, depth, borrowPercent) => { + borrowPercent = new BigNumber(borrowPercent); + let leveragedSupplyBase = new BigNumber(0); + let leveragedBorrowBase = new BigNumber(0); + let leveragedSupplyVxs = new BigNumber(0); + let leveragedBorrowVxs = new BigNumber(0); + + for (let i = 0; i < depth; i++) + { + leveragedSupplyBase = leveragedSupplyBase.plus( + supplyBase.times(borrowPercent.exponentiatedBy(i)) + ); + leveragedSupplyVxs = leveragedSupplyVxs.plus(supplyVxs.times(borrowPercent.exponentiatedBy(i))); + leveragedBorrowBase = leveragedBorrowBase.plus( + borrowBase.times(borrowPercent.exponentiatedBy(i + 1)) + ); + leveragedBorrowVxs = leveragedBorrowVxs.plus( + borrowVxs.times(borrowPercent.exponentiatedBy(i + 1)) + ); + } + return { + leveragedSupplyBase, + leveragedBorrowBase, + leveragedSupplyVxs, + leveragedBorrowVxs, + }; +}; + +module.exports = getTranquilApys; diff --git a/tranquilLpPools.json b/tranquilLpPools.json new file mode 100644 index 0000000..b39ac59 --- /dev/null +++ b/tranquilLpPools.json @@ -0,0 +1,65 @@ +[ + { + "name": "tranquil-usdc", + "tqToken": "0xCa3e902eFdb2a410C952Fd3e4ac38d7DBDCB8E96", + "oracle": "tokens", + "oracleId": "USDC", + "decimals": "1e18", + "borrowDepth": 6, + "borrowPercent": 0.888 + }, + { + "name": "tranquil-wbtc", + "tqToken": "0xd9c0D8Ad06ABE10aB29655ff98DcAAA0E059184A", + "oracle": "tokens", + "oracleId": "BTC", + "decimals": "1e18", + "borrowDepth": 6, + "borrowPercent": -0.5 + }, + { + "name": "tranquil-eth", + "tqToken": "0xc63AB8c72e636C9961c5e9288b697eC5F0B8E1F7", + "oracle": "tokens", + "oracleId": "1ETH", + "decimals": "1e18", + "borrowDepth": 6, + "borrowPercent": -0.675 + }, + { + "name": "tranquil-1btc", + "tqToken": "0x481721B918c698ff5f253c56684bAC8dCa84346c", + "oracle": "tokens", + "oracleId": "1BTC", + "decimals": "1e18", + "borrowDepth": 6, + "borrowPercent": -0.5 + }, + { + "name": "tranquil-stone", + "tqToken": "0x973f22036A0fF3A93654e7829444ec64CB37BD78", + "oracle": "tokens", + "oracleId": "stONE", + "decimals": "1e18", + "borrowDepth": 6, + "borrowPercent": 1.044 + }, + { + "name": "tranquil-wone", + "tqToken": "0x34B9aa82D89AE04f0f546Ca5eC9C93eFE1288940", + "oracle": "tokens", + "oracleId": "WONE", + "decimals": "1e18", + "borrowDepth": 6, + "borrowPercent": -0.5 + }, + { + "name": "tranquil-dai", + "tqToken": "0x49d95736FE7f1F32E3ee5deFc26c95bA22834639", + "oracle": "tokens", + "oracleId": "1DAI", + "decimals": "1e18", + "borrowDepth": 6, + "borrowPercent": -0.5 + } +] \ No newline at end of file