From eb415c4860e26d9913b743d2f6af85a0414ef6bc Mon Sep 17 00:00:00 2001 From: sahil shimpi Date: Fri, 24 Feb 2023 22:25:32 +0530 Subject: [PATCH] index files added --- .DS_Store | Bin 10244 -> 12292 bytes Array/.DS_Store | Bin 0 -> 6148 bytes Array/ArrayProbs.java/aread.txt | 4 +- Array/ArrayProbs.java/array_prob10.java | 31 ++++ Array/ArrayProbs.java/array_prob12.java | 43 ++++++ Array/ArrayProbs.java/array_prob16.java | 1 + Array/ArrayProbs.java/array_prob17.java | 97 ++++-------- Array/ArrayProbs.java/array_prob18.java | 3 + Array/ArrayProbs.java/array_prob26.java | 21 +++ Array/ArrayProbs.java/array_prob27.java | 2 +- Array/ArrayProbs.java/array_prob28.class | Bin 0 -> 2887 bytes Array/ArrayProbs.java/array_prob28.java | 183 +++++++++++++++++++++++ Array/ArrayProbs.java/array_prob29.class | Bin 0 -> 1475 bytes Array/ArrayProbs.java/array_prob29.java | 90 +++++++++++ Array/ArrayProbs.java/array_prob3.class | Bin 1145 -> 1149 bytes Array/ArrayProbs.java/array_prob3.java | 2 +- Array/ArrayProbs.java/array_prob30.class | Bin 0 -> 1292 bytes Array/ArrayProbs.java/array_prob30.java | 44 ++++++ Array/ArrayProbs.java/array_prob31.class | Bin 0 -> 900 bytes Array/ArrayProbs.java/array_prob31.java | 48 ++++++ Array/ArrayProbs.java/array_prob32.java | 92 ++++++++++++ Array/ArrayProbs.java/array_prob33.class | Bin 0 -> 1132 bytes Array/ArrayProbs.java/array_prob33.java | 100 +++++++++++++ Array/ArrayProbs.java/array_prob34.class | Bin 0 -> 1280 bytes Array/ArrayProbs.java/array_prob34.java | 124 +++++++++++++++ Array/ArrayProbs.java/array_prob35.java | 29 ++++ Array/ArrayProbs.java/array_prob6.java | 8 + Array/ArrayProbs.java/array_prob7.java | 23 +++ Array/ArrayProbs.java/array_prob8.java | 40 ++++- Array/ArrayProbs.java/array_prob9.java | 10 +- Array/exmp.class | Bin 0 -> 1047 bytes Array/exmp.java | 34 +++-- Bit/bit_prob_4.class | Bin 1068 -> 1324 bytes Bit/bit_prob_4.java | 52 +++++++ DP/{index.txt => aindex.txt} | 0 DP/dp_prob10.class | Bin 1293 -> 1293 bytes DP/dp_prob10.java | 4 +- DP/dp_prob11.java | 41 ++--- DP/dp_prob15.class | Bin 1583 -> 1777 bytes DP/dp_prob15.java | 13 +- DP/dp_prob18.class | Bin 1206 -> 1214 bytes DP/dp_prob20.java | 2 +- DP/dp_prob22.java | 4 +- DP/dp_prob23.java | 1 - DP/dp_prob27.class | Bin 1244 -> 1702 bytes DP/dp_prob27.java | 28 ++++ DP/dp_prob30.class | Bin 656 -> 650 bytes DP/dp_prob30.java | 5 +- DP/dp_prob32.java | 7 + DP/dp_prob33.class | Bin 1454 -> 1558 bytes DP/dp_prob33.java | 21 ++- DP/dp_prob40.java | 1 - DP/dp_prob41.class | Bin 0 -> 1171 bytes DP/dp_prob41.java | 37 +++++ DP/dp_prob42.java | 45 ++++++ DP/dp_prob43.java | 50 +++++++ DP/dp_prob44.class | Bin 0 -> 1075 bytes DP/dp_prob44.java | 58 +++++++ GPP/abhyas.java | 101 ------------- Graph/prob11_graph$Edge.class | Bin 450 -> 450 bytes Graph/prob11_graph.class | Bin 2313 -> 2313 bytes Graph/prob11_graph.java | 1 - Graph/prob13_graph.class | Bin 1951 -> 1951 bytes Graph/prob13_graph.java | 3 +- Graph/prob16_graph.class | Bin 1862 -> 1862 bytes Graph/prob16_graph.java | 13 +- Graph/prob17_graph.java | 6 +- Graph/prob20_graph.java | 6 +- Graph/prob4_graph.class | Bin 1924 -> 3085 bytes Graph/prob4_graph.java | 50 ++++++- Graph/prob6_graph.java | 2 +- Graph/prob7_graph.class | Bin 1938 -> 1938 bytes Graph/prob7_graph.java | 2 + Graph/prob9_graph.java | 2 + HackerEarth.java | 49 +++--- Heap&Hashing/prob1.java | 1 - Heap&Hashing/prob10.java | 2 - Heap&Hashing/prob15.class | Bin 558 -> 578 bytes Heap&Hashing/prob15.java | 2 +- Heap&Hashing/prob18.java | 83 ++++++++++ Heap&Hashing/prob2.java | 2 - Heap&Hashing/prob3.java | 18 ++- Heap&Hashing/prob4.java | 2 + Heap&Hashing/prob5.class | Bin 1049 -> 1045 bytes Heap&Hashing/prob5.java | 3 + Heap&Hashing/prob6.java | 1 - Linkedlist/.DS_Store | Bin 0 -> 6148 bytes Linkedlist/aindex.txt | 29 ++++ Linkedlist/prob17.java | 4 +- Linkedlist/prob19.java | 2 +- Linkedlist/prob2.java | 5 +- Linkedlist/prob25$Node.class | Bin 0 -> 410 bytes Linkedlist/prob25.class | Bin 0 -> 2026 bytes Linkedlist/prob25.java | 18 ++- Linkedlist/prob27.java | 2 + Linkedlist/prob29.java | 143 +++--------------- Linkedlist/prob6$Node.class | Bin 0 -> 355 bytes Linkedlist/prob6.class | Bin 0 -> 1873 bytes Linkedlist/prob6.java | 73 ++++++++- Searching&sorting/prob12.class | Bin 1261 -> 1261 bytes Searching&sorting/prob12.java | 4 + Searching&sorting/prob9.java | 3 +- SegmentTree/prob3.class | Bin 0 -> 1215 bytes SegmentTree/prob3.java | 54 +++++++ SegmentTree/prob4$1.class | Bin 0 -> 630 bytes SegmentTree/prob4.class | Bin 0 -> 1666 bytes SegmentTree/prob4.java | 60 ++++++++ SegmentTree/prob5$Node.class | Bin 0 -> 658 bytes SegmentTree/prob5.class | Bin 0 -> 2197 bytes SegmentTree/prob5.java | 58 +++++++ SegmentTree/prob6.class | Bin 0 -> 1804 bytes SegmentTree/prob6.java | 128 ++++++++++++++++ Stack/.DS_Store | Bin 0 -> 6148 bytes String/{1_index.txt => aindex.txt} | 0 String/intr.java | 55 +++++++ String/intr2.java | 41 +++++ String/list$Node.class | Bin 0 -> 351 bytes String/list.class | Bin 0 -> 1014 bytes String/list.java | 66 ++++++++ String/prob_str27.java | 27 ++++ String/prob_str28.java | 51 +++++++ String/prob_str29.class | Bin 0 -> 1597 bytes String/prob_str29.java | 79 ++++++++++ String/prob_str4.class | Bin 1204 -> 1969 bytes String/prob_str4.java | 7 +- String/prob_str6.class | Bin 1184 -> 1978 bytes String/prob_str6.java | 33 +++- String/prob_str7.class | Bin 1348 -> 1439 bytes String/prob_str7.java | 7 +- Tree/.DS_Store | Bin 6148 -> 6148 bytes Tree/BST/prob2.java | 1 - Tree/BST/prob9.java | 2 +- Tree/Bt/Subtree.java | 12 ++ Tree/Bt/prob1.java | 8 + Tree/Bt/prob10.java | 15 ++ Tree/Bt/prob14.class | Bin 2189 -> 2189 bytes Tree/Bt/prob14.java | 1 - Tree/Bt/prob16.class | Bin 2401 -> 3020 bytes Tree/Bt/prob16.java | 51 ++++++- Tree/Bt/prob17.class | Bin 1951 -> 2981 bytes Tree/Bt/prob17.java | 39 ++++- Tree/Bt/prob19.java | 110 +++++++++----- Tree/Bt/prob2.java | 9 +- Tree/Bt/prob23.class | Bin 0 -> 1963 bytes Tree/Bt/prob23.java | 4 +- Tree/Bt/prob24.class | Bin 2167 -> 1763 bytes Tree/Bt/prob25.java | 34 +++++ Tree/Bt/prob26.class | Bin 2192 -> 2192 bytes Tree/Bt/prob28$Node.class | Bin 0 -> 441 bytes Tree/Bt/prob28.class | Bin 0 -> 1717 bytes Tree/Bt/prob28.java | 17 +-- Tree/Bt/prob3.java | 20 +++ Tree/Bt/prob4.java | 7 + Tree/TreeProblems/tree_prob1.java | 4 +- backtracking/aread.txt | 5 + backtracking/bt_prob2.java | 1 - backtracking/bt_prob3.class | Bin 0 -> 2013 bytes backtracking/bt_prob3.java | 59 +++++++- backtracking/bt_prob4.class | Bin 0 -> 1578 bytes backtracking/bt_prob4.java | 45 ++++++ backtracking/bt_prob5.class | Bin 0 -> 2115 bytes backtracking/bt_prob5.java | 94 ++++++++++++ backtracking/bt_prob6.class | Bin 0 -> 1704 bytes backtracking/bt_prob6.java | 90 +++++++++++ backtracking/bt_prob7.class | Bin 0 -> 2523 bytes backtracking/bt_prob7.java | 60 ++++++++ backtracking/bt_prob8.class | Bin 0 -> 1240 bytes backtracking/bt_prob8.java | 30 ++++ backtracking/bt_prob9.java | 5 + bitsort.class | Bin 0 -> 3140 bytes bitsort.java | 47 ++++++ 171 files changed, 2994 insertions(+), 472 deletions(-) create mode 100644 Array/.DS_Store create mode 100644 Array/ArrayProbs.java/array_prob28.class create mode 100644 Array/ArrayProbs.java/array_prob28.java create mode 100644 Array/ArrayProbs.java/array_prob29.class create mode 100644 Array/ArrayProbs.java/array_prob29.java create mode 100644 Array/ArrayProbs.java/array_prob30.class create mode 100644 Array/ArrayProbs.java/array_prob30.java create mode 100644 Array/ArrayProbs.java/array_prob31.class create mode 100644 Array/ArrayProbs.java/array_prob31.java create mode 100644 Array/ArrayProbs.java/array_prob32.java create mode 100644 Array/ArrayProbs.java/array_prob33.class create mode 100644 Array/ArrayProbs.java/array_prob33.java create mode 100644 Array/ArrayProbs.java/array_prob34.class create mode 100644 Array/ArrayProbs.java/array_prob34.java create mode 100644 Array/ArrayProbs.java/array_prob35.java create mode 100644 Array/exmp.class rename DP/{index.txt => aindex.txt} (100%) create mode 100644 DP/dp_prob41.class create mode 100644 DP/dp_prob41.java create mode 100644 DP/dp_prob42.java create mode 100644 DP/dp_prob43.java create mode 100644 DP/dp_prob44.class create mode 100644 DP/dp_prob44.java delete mode 100644 GPP/abhyas.java create mode 100644 Heap&Hashing/prob18.java create mode 100644 Linkedlist/.DS_Store create mode 100644 Linkedlist/aindex.txt create mode 100644 Linkedlist/prob25$Node.class create mode 100644 Linkedlist/prob25.class create mode 100644 Linkedlist/prob6$Node.class create mode 100644 Linkedlist/prob6.class create mode 100644 SegmentTree/prob3.class create mode 100644 SegmentTree/prob3.java create mode 100644 SegmentTree/prob4$1.class create mode 100644 SegmentTree/prob4.class create mode 100644 SegmentTree/prob4.java create mode 100644 SegmentTree/prob5$Node.class create mode 100644 SegmentTree/prob5.class create mode 100644 SegmentTree/prob5.java create mode 100644 SegmentTree/prob6.class create mode 100644 SegmentTree/prob6.java create mode 100644 Stack/.DS_Store rename String/{1_index.txt => aindex.txt} (100%) create mode 100644 String/intr.java create mode 100644 String/intr2.java create mode 100644 String/list$Node.class create mode 100644 String/list.class create mode 100644 String/list.java create mode 100644 String/prob_str27.java create mode 100644 String/prob_str28.java create mode 100644 String/prob_str29.class create mode 100644 String/prob_str29.java create mode 100644 Tree/Bt/Subtree.java create mode 100644 Tree/Bt/prob23.class create mode 100644 Tree/Bt/prob28$Node.class create mode 100644 Tree/Bt/prob28.class create mode 100644 backtracking/aread.txt create mode 100644 backtracking/bt_prob3.class create mode 100644 backtracking/bt_prob4.class create mode 100644 backtracking/bt_prob4.java create mode 100644 backtracking/bt_prob5.class create mode 100644 backtracking/bt_prob5.java create mode 100644 backtracking/bt_prob6.class create mode 100644 backtracking/bt_prob6.java create mode 100644 backtracking/bt_prob7.class create mode 100644 backtracking/bt_prob7.java create mode 100644 backtracking/bt_prob8.class create mode 100644 backtracking/bt_prob8.java create mode 100644 backtracking/bt_prob9.java create mode 100644 bitsort.class create mode 100644 bitsort.java diff --git a/.DS_Store b/.DS_Store index 7075698243ab74b404dbde8ec80251eb1b5b6de9..3bf2af1ba10d89875084322131643fe1638e6fce 100644 GIT binary patch literal 12292 zcmeHNU5pe(5U$?ayW8VO_J9L_QhWpiyAiI|2xVlfA$ZkYj&_y@B1C&CJ{n z5|WJ%8Z{bT)dzVpF)Yl2uo+ToYn=TI%ttFxqZds<6;PEU`W--dpCHv*wc6Fge;C67Mo+c{MX)^G8 zCl%VL+Zz&SlKe^BY1$2*Fuy|{P0>a=h4vXL?5WzNV%07xTIw1B>$uRT7ul$K$cyn zH7W~tk$0P9QHAH+$rnNUW-I4jfUjB!<=SGPy3iOkdo+}{H;(0ws=PfC6VLOnP0#ZF z#Anh1%awL@n#KvkPMU+}HRxW24L0HgqKe-xxmTa0f@v9!Vlc}FNRAygt+G9vv!|`Ht9bK% zN2)K?H<@02_Uz^@8#2Sg51rePIs3?_hc{%lY#usyt}it(_`stFCr?*vmi?TxI@Aw* zH!bylx1P_V)=@RHG!v*MK5eS@eLCG#u5Z!eB};ExmhNA^qJL%oz`&~2w-4NL=bd*? zrdJdTrPCEhf*!G}wv($)8xv;9w({mv#)N0gd9pH@Uarv{G|I>4o5s)7L9=qcLCM0GU;+W+FCr`SDHxa5InM^NpOO9Qwj@hp1nYMN0mFY>!ghlXJG3Cb=l<} zG8`9W8_&d%g5wmdijh0>WVKKONOwv4{M!R+3kB}MD8@*k%>Ji;u!M6b~6^gew= zU(+x2r$~xb;y$rnJSet`?P9lhLL3w&F(piK%I8lsC;T2hl5p|68yI%rbtB>Psd~p8J z;Pf>ZgJW#(=lF&o8Xh*UqLKrj9K<8UCzotk*#q*n_#|G?EPWjkxK5XkU*EV~Te>>1 zUuk@N&N*EK&aI)@`osyPU7-w7$wxJ>Ek-bl|GDu>C%CM>5;r3_2^MZrGIOG z@4i5Pcn%mXN89_hE=$APTun?y#2R8W40G3ci8R6kn{ZT$>) zGoDNI@fBMjw!qD9flW}L^^KhQk%1pig!{N3Y5%^?{a<@O^CSNE_g>`NGuY9U5Z}vW zu+b^;4o24~IEF^|$o3#sGdUbd6cxim84QLfx&uDZK|DUgqp_Gn@3v6H2vIWBU0p+5 zj)r)u6^&aXX=po8Fr=w02Ed6;(cd+woWuX$M2EV~6X35X5n*j#PJenR6DmoD<=y2*nX_}wx~X)ea{7m!<_7*u{JbvPQvefK*jL%4F5XMuOZs^ zvA;_U`1qVOv|fg4c?Lq^Np~qfTBoTFb_&0PAxefW@k5!*(GY&~#++I;A$|>I2MUI? z`vL|)UL%nrYla8WyuLbp4P#}r3@!a3=b!a+ymZmntMF6h4!rZO|@Sbs>rvd5?#>sO=9>(;87h#rG<>c|zMHwAHk^B(c_on4O>~ zu3af^1O*jD7cK+##JaxhXD0ip-RIPdev2XTEdh%-lN( z5t)%=r6Hmm5oK|)?CZrXp|PH?wwAIz`ymbNsWLe~HPrdN=kW(uH&ZPXCMwkl^zl+_jJ$t1to5Zu_0g2`-N5ECm{JeMoufJxsY)d( ztI;X-s2$;P$o}y_ICy?$s)|Vml;RU_HeEDKHT;d!i9MBS(MF36#ms}twr|pyI5|kg z+WgzEwVH7=vWy*j%{B?4n5LUNelJacWs#0jL-_KiX_}=;%{%o!umcY7j&>>vT6KT1 zG2ECQ+&%UD^IMsPj=tRpe*~}Mr2`!AS{jk~#u4oa8l^I#uOa>^`V0S6pex1kV%=cVN5(l+Mt>H9%Q=Hy?Ml-M)JDwdA9vU8u%(t%}u1tSKtc z0guxyjONaxU=*X&N`5d(zsrZH`DxEf;bV0RYny? zIU4so-0(asqrKwesKm-EqE23AOT_NHCEBQ2G%vOw+C-c;r-u){lPc?gRaLhrR?T@BwP;O;)LaF%U6M^SvZnQRAsm@M<2k)a@h^>K| z!*f;7pR9g&4LL|1(-VG6a^x z;5_WqSPQ3PJHv01Eu9+|o;Dj+Z?tR4j^W0Xq*w8n3vj*Q+p8khg%&apG7vJb6f=;H zN#*$a|DBzG|6hvK1E-LIkb$3+0h1|=7Wf5_UwxArf7hPFHHM2DW=0x@YZ(%IA48^96gDU#~u1-iDi^${nKSx3XKlMw5Mr6AZE7 zHNg`uh#m!J*T)?_OH6cs#SHhn+Me-azW0mEcbV^&aVp=K|BhLW^(3#d9us507%&F* zjRDqdk?yggS!2K$Fb38P$oC&#qjB%2}b~8LU$0h!#^A`6$dekSS!*)ahgih zR2PpJPSfd6V_X)oR@8L3FfyMLM|Saq;=<_kry(3JQ#5M~7z0fP4)nGs_5b|$^M5nR z?u-Fr;9oJ|l6;(xxTIKHTZ@xgn^Lc+A`(|Cu2a|urI@i&ichIQ=uf3V%p%r`^ib?a NAkbjO82D2LJ^{$iSQ!8S literal 0 HcmV?d00001 diff --git a/Array/ArrayProbs.java/aread.txt b/Array/ArrayProbs.java/aread.txt index 07fbd65..53c9e5a 100644 --- a/Array/ArrayProbs.java/aread.txt +++ b/Array/ArrayProbs.java/aread.txt @@ -23,4 +23,6 @@ 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 +27.next smaller +28.29.array rearrangements +30.Minimum number of swaps required to sort an array \ No newline at end of file diff --git a/Array/ArrayProbs.java/array_prob10.java b/Array/ArrayProbs.java/array_prob10.java index 1e0b0e1..25da9aa 100644 --- a/Array/ArrayProbs.java/array_prob10.java +++ b/Array/ArrayProbs.java/array_prob10.java @@ -1,3 +1,5 @@ +import java.util.*; + //stock busy sell to maximum profit // Solution structure class Interval { @@ -5,6 +7,7 @@ class Interval { } public class array_prob10 { + // at most 1 time public static int maxProfit(int prices[]) { int minPrice = Integer.MAX_VALUE; int maxProfit = 0; @@ -74,6 +77,34 @@ void stockBuySell(int price[], int n) { } + void stockBuySellR(int price[], int n) { + if (n == 1) + return; + + int count = 0; + ArrayList list = new ArrayList<>(); + int i = 0; + while (i < n - 1) { + while ((i < n - 1) && price[i] > price[i + 1]) { + i++; + } + + if (i == n - 1) { + break; + } + Interval s = new Interval(); + s.buy = i++; + while ((i < n) && price[i] > price[i - 1]) { + i++; + } + + s.sell = i - 1; + list.add(s); + count++; + + } + } + public static void main(String[] args) { int arr[] = { 100, 180, 260, 310, 40, 535, 695 }; System.out.println(maxProfit(arr)); diff --git a/Array/ArrayProbs.java/array_prob12.java b/Array/ArrayProbs.java/array_prob12.java index 6a521c4..dc6ca05 100644 --- a/Array/ArrayProbs.java/array_prob12.java +++ b/Array/ArrayProbs.java/array_prob12.java @@ -3,6 +3,49 @@ //trappping rainwater public class array_prob12 { + + /** + * Time Complexity: O(N) + * Auxiliary Space: O(N) + * + */ + + /** + * Brute Approach + * Traverse every array element and find the highest bars on the left and right + * sides. Take the smaller of two heights. The difference between the smaller + * height and the height of the current element is the amount of water that can + * be stored in this array element. + */ + + public static int maxWater(int[] arr, int n) { + + // To store the maximum water + // that can be stored + int res = 0; + + // For every element of the array + // except first and last element + for (int i = 1; i < n - 1; i++) { + + // Find maximum element on its left + int left = arr[i]; + for (int j = 0; j < i; j++) { + left = Math.max(left, arr[j]); + } + + // Find maximum element on its right + int right = arr[i]; + for (int j = i + 1; j < n; j++) { + right = Math.max(right, arr[j]); + } + + // Update maximum water value + res += Math.min(left, right) - arr[i]; + } + return res; + } + public static int trapingRainwater(int arr[]) { Stack s = new Stack<>(); int ans = 0; diff --git a/Array/ArrayProbs.java/array_prob16.java b/Array/ArrayProbs.java/array_prob16.java index 64d424a..6fc27c3 100644 --- a/Array/ArrayProbs.java/array_prob16.java +++ b/Array/ArrayProbs.java/array_prob16.java @@ -76,6 +76,7 @@ void productArray2(int arr[], int n) { public static void main(String[] args) { array_prob16 pa = new array_prob16(); int arr[] = { 10, 3, 5, 6, 2 }; + int n = arr.length; System.out.println("The product array is : "); pa.productArray(arr, n); diff --git a/Array/ArrayProbs.java/array_prob17.java b/Array/ArrayProbs.java/array_prob17.java index cd25043..43b12a0 100644 --- a/Array/ArrayProbs.java/array_prob17.java +++ b/Array/ArrayProbs.java/array_prob17.java @@ -61,76 +61,41 @@ public static List> findTriplets(int[] nums, int sum) { return pair; } - public static void findTriplets2(int a[], int n, int sum) { - int i; - - // Sort the input array - Arrays.sort(a); - - // For handling the cases when no such - // triplets exits. - boolean flag = false; - - // Iterate over the array from start to n-2. - for (i = 0; i < n - 2; i++) { - if (i == 0 || a[i] > a[i - 1]) { - // Index of the first element in - // remaining range. - int start = i + 1; - - // Index of the last element - int end = n - 1; - - // Setting our new target - int target = sum - a[i]; - - while (start < end) { - // Checking if current element - // is same as previous - if (start > i + 1 - && a[start] == a[start - 1]) { - start++; - continue; - } - - // Checking if current element is - // same as previous - if (end < n - 1 - && a[end] == a[end + 1]) { - end--; - continue; - } + // target 0 + public static List> threeSum(int[] nums) { - // If we found the triplets then print it - // and set the flag - if (target == a[start] + a[end]) { - System.out.print("[" + a[i] - + "," + a[start] - + "," + a[end] + "] "); - flag = true; - start++; - end--; - } - - // If target is greater then - // increment the start index - else if (target > (a[start] + a[end])) { - start++; - } - - // If target is smaller than - // decrement the end index - else { - end--; - } - } + List> ans = new ArrayList>(); + Arrays.sort(nums); + int n = nums.length; + + for (int i = 0; i < n; i++) { + int p = i + 1, q = n - 1; + while (p < q) { + if (nums[p] + nums[q] == -nums[i]) { // System.out.println(p+" "+q); + List t = new ArrayList(); + t.add(nums[i]); + t.add(nums[p]); + t.add(nums[q]); + + ans.add(t); + + while (p + 1 < q && nums[p + 1] == nums[p]) + p++; + while (q - 1 > p && nums[q - 1] == nums[q]) + q--; + + p++; + q--; + } else if (nums[p] + nums[q] < -nums[i]) + p++; + else + q--; } - } - // If no such triplets found - if (flag == false) { - System.out.print("No Such Triplets Exist"); + while (i + 1 < n && nums[i + 1] == nums[i]) + i++; } + return ans; } // Driver code diff --git a/Array/ArrayProbs.java/array_prob18.java b/Array/ArrayProbs.java/array_prob18.java index 2a2ea5a..d39b5b2 100644 --- a/Array/ArrayProbs.java/array_prob18.java +++ b/Array/ArrayProbs.java/array_prob18.java @@ -19,6 +19,9 @@ public int compare(Interval i1, Interval i2) { } }); + + + int index = 0; // // i = 1 for (int i = 1; i < arr.length; i++) { diff --git a/Array/ArrayProbs.java/array_prob26.java b/Array/ArrayProbs.java/array_prob26.java index a2761cb..4591d6e 100644 --- a/Array/ArrayProbs.java/array_prob26.java +++ b/Array/ArrayProbs.java/array_prob26.java @@ -3,6 +3,27 @@ import java.util.Stack; public class array_prob26 { + + /* + * prints element and NGE pair for + * all elements of arr[] of size n + * + * O(n2) + */ + static void printNG1(int arr[], int n) { + int next, i, j; + for (i = 0; i < n; i++) { + next = -1; + for (j = i + 1; j < n; j++) { + if (arr[i] < arr[j]) { + next = arr[j]; + break; + } + } + System.out.println(arr[i] + " -- " + next); + } + } + public static void nextGreater(int arr[], int n) { int i = 0; Stack s = new Stack<>(); diff --git a/Array/ArrayProbs.java/array_prob27.java b/Array/ArrayProbs.java/array_prob27.java index 22aeb07..2674f38 100644 --- a/Array/ArrayProbs.java/array_prob27.java +++ b/Array/ArrayProbs.java/array_prob27.java @@ -38,7 +38,7 @@ public static void nextSmaller(int arr[], int n) { next = -1; // System.out.println(element + "-->" + next); map.put(element, next); - } + for (i = 0; i < n; i++) { System.out.println(arr[i] + " --> " + map.get(arr[i])); diff --git a/Array/ArrayProbs.java/array_prob28.class b/Array/ArrayProbs.java/array_prob28.class new file mode 100644 index 0000000000000000000000000000000000000000..80a82625071810ceaf6ab71228c4eb73b4093816 GIT binary patch literal 2887 zcmbVNOK=ob6g_Xcr+YFCW(W=;WEv7aAsNDi?*IvjKqMp@(nu&EL<>4e14AY=ai$Y1 zsQ8QJ&hi5)AAt&`snV5JDIYa1bmh_oE30H-xp4ud8?=OYUe6?%Bot*)mAu#Q_U-%b zx#!$FKi$7E24EBR_%Rpdek{eZ0xZXhB3i5bh+vhDYCklT&%q+BmP=H=tMMa%H9FSn zSSO%ujVI$ygMd<5wO>GOO!e3Tg{|?V-8RtIWvBO9T?txzRyu7ZkJ)Plyp^3T(sypV zV|DlLw)$Nc9qXsO7qZ?s`Ex-x9^Nr^ST7H1pA}CEEU4^kJz))6H3{Bb z)9$3>$zyf$Zhw1fAl+>@#bs{uWSF7D{pnQKy3JAPAHZWM)Uh#u7&htH9KaUT3Iung zQclK6Tm8Fj=Xk0oQ>dZNhphqBqd~_L0c^u|#&fS6aN>!YW-D{N-F5=lfyMxyluJE! z2CxA01p@i^GWt}eX4eV3+Y#_|wy;i9;TUQnyo;zM>Db5Yw17TnB?fHssD#{7m4`X! zQ8z7o`%uQQ`^Z^pfbl|E_jsyi59{NwO19Nk=SLHEF#}O1P~2zr+Ks7Xx8)p&JIDEy zajc}15m;IIfV=YV&(&ODzKde|CDcN{yplQO$I0VKv3h!Dyv^38uIdog(49&;B$|nY zro+yK(9tXl-YT$ss<`pwV5-;7sUeH1$?A4e=^-6$RCH@9)jQBndRmf6JKdPDG8vmU ze3YMJE=E=c%~rA}VP}?SKdj5ENG^>$%d`*o4fWd(aL?E51lrjl8m&a4J?_|bI!u8T zv+zAAH-W_u_d_|GdoH^iD1eY%z%|H|!Ci3oMy^79!3XM)tL7RNIu~I+pQY;`P~qeL zVq|QqTCX&OOGi)?2}iyC>SYuRdpx7#w+-6nMGV@`(WKCHN4k|t`vUsL)JT}G&4>|F z&C&7iBeiOYIu`RPF)gHpydx+pQA1kv8a%c7mrzRd8@v=>!#k{r(eYnpf*v=)9d1e* z6zK3WEggP@FbAbXSxJ0RzTZsGdID%9gl0UBr?C*nPy&bhNrY(u8&MlP2V%?h4YqMGQ}VHM|pHMU|k=Tj8BP=lwi7DxFe z!+i)FT>W)+Zs8-#;a_lbEI9VTAwq$iTCNZzk|9 z1YS$RCAAHtavMvq9aWsd>#>uhH_^I_q&M@)L>KlT#eD#KrxP9w&LDi@BY^6-7``xolLd5M7s{32M2~_n!ja%mscBX$LlEY;4J(R z!!SpoM+}eY;=VN_*#E>`%N7OVOzs4mwwD4B^FfoCbu4nB19!3bUkI^KnN^U|iGtuIa?6o|^)9zktE))nMJ(YOzJ!Gl z?$HLh@{b%7?)WcmbKjhzt%5ZMUS|5I*nzK*u2)IdYozLR3h@o5H_Tpp%T09-lzZ?B zQNg76S$HB7QI_khGt9)pd73SEClz)93wR^%pEfR)m>O1(NP#iwXh@aga%Ci>(!ES> zF^y}4vNO4aG?OF_t8B=hU7|jn)p<*%joR=HBAJ}Dc@o{vxeB~PtnacZ-Xn4E6W3{C zK0`1cP@*4l?wsX}Imf0uj}}~@Oh2YfFH*>tDB#OD!tah^gw?r%x4ECjCvI&FIe`i| zfsA`{2>*>W6!OFnmO?hLI5&iwSS=3|sR(M{`a6{1J+ng%YG#Kw7%)3DkJ+L7%no1h zuGzZk8s&BCj?2$U&sRJx;n{;S{v3di1ry%Q@mPWio_##8= 0 && arr[r] > 0) { + r--; + } + + if (l < r) { + int temp = arr[l]; + arr[l] = arr[r]; + arr[r] = temp; + } + } + for (Integer i : arr) { + System.out.print(i + " "); + } + } + + // negative positive alternate + public static void arrange3(int arr[]) { + int n = arr.length; + int nIndex = 0; + int pIndex = 1; + + while (true) { + while (nIndex < n && arr[nIndex] < 0) { + nIndex += 2; + } + while (pIndex < n && arr[pIndex] > 0) { + pIndex += 2; + } + + if (nIndex < n && pIndex < n) { + int temp = arr[nIndex]; + arr[nIndex] = arr[pIndex]; + arr[pIndex] = temp; + } + + else { + break; + } + + } + for (Integer i : arr) { + System.out.print(i + " "); + } + } + + // move all o at end + public static void arrange4(int arr[]) { + int n = arr.length; + int j = 0; // last index for non zero + for (int i = 0; i < n; i++) { + if (arr[i] != 0) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + j++; + } + } + + for (Integer i : arr) { + System.out.print(i + " "); + } + + } + + // Rearrange an array such that arr[i] = i + public static void arrange5(int arr[]) { + int n = arr.length; + Set s = new HashSet<>(); + for (Integer i : arr) { + s.add(i); + } + + for (int i = 0; i < n; i++) { + if (s.contains(i)) { + arr[i] = i; + } else { + arr[i] = -1; + } + } + for (Integer i : arr) { + System.out.print(i + " "); + } + } + + // cyclic sort + public static void arrange5_B(int arr[]) { + int n = arr.length; + for (int i = 0; i < n;) { + if (arr[i] > 0 && arr[i] != i) { + int temp = arr[arr[i]]; + arr[arr[i]] = arr[i]; + arr[i] = temp; + } else { + i++; + } + } + } + + // Rearrange positive and negative numbers in O(n) time and O(1) extra space + /** + * + * For example, if the input array is [-1, 2, -3, 4, 5, 6, -7, 8, 9], then the + * output should be [9, -7, 8, -3, 5, -1, 2, 4, 6] + */ + public static void arrange3_B(int arr[]) { + int n = arr.length; + int i = -1, j = 0; + for (j = 0; j < n; j++) { + if (arr[j] < 0) { + i++; + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + int neg = 0, pos = i + 1; + while (pos < n && neg < pos && arr[neg] < 0) { + int temp = arr[neg]; + arr[neg] = arr[pos]; + arr[pos] = temp; + pos++; + neg += 2; + } + for (Integer k : arr) { + System.out.print(i + " "); + } + } + + public static void main(String[] args) { + // int arr[] = { 3, 6, 12, 1, 5, 8 }; + // arrange1(arr); + int arr[] = { -3, 6, 12, -1, 5, -8 }; + arrange2(arr); + // int arr[] = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; + // arrange3(arr); + // arrange3_B(arr); + // int[] arr = { 5, 6, 0, 4, 6, 0, 9, 0, 8 }; + // arrange4(arr); + // int arr[] = { -1, -1, 6, 1, 9, + // 3, 2, -1, 4, -1 }; + // arrange5(arr); + + } + +} diff --git a/Array/ArrayProbs.java/array_prob29.class b/Array/ArrayProbs.java/array_prob29.class new file mode 100644 index 0000000000000000000000000000000000000000..bc98a0d1a5f846b57efa1a6fe6a25997daf28a52 GIT binary patch literal 1475 zcmZ8g&u<$=6#mBhD|Q^$NxG)4y=_9$Vs9EJO=FNNG_r95*4xb(X zcpH}^2;+1FDWt=&a3+GY7?I0SIeRmLK8zU{H*iiszgnx;+64h6lU){2Z!{{Nz=_3L z-CNq+D0{7YZh4&^W206teeO0n%d8fQ#cWYvpwxEPKD*;KgP6o4uiEmeZrfYf^6J;U z2aT5JR4ObYk7Sn(oEL~O$m>Qq7w=#DzoSeH8*Z&GkjShqK6JO-sdcwrohr3kwR&|< zVvLj;o2@nPW=-N6bXzU=@%?72QJ#4>C*z}tpx?k-QDl%cU`H{53kD{m$YCmqXq0wU|AEHHerymag>p zQQO;KpBtM@YIehGjj6lj)h0X7-Qa;?zs_+tD>Y@%I-6ol6negO>z_iiW!C9f)Z z&D2u6xMG`HF8wva+ltu3sP!c*>B;LH`LilH$2ZdHY-?h#^Ruab%QPXsP>x7goh#i> zA0y5Lk)~OCgnQ?Sa+;B|Ed3th{J@oZh(002u=Rq6A{fL_fbj>YOaOconkUMFMS$bB zmD8F#NNk6MozCS|J57&cTc+wr%$;BDSv9F1t;sNn;=C zw$8{uWP`f6XZ-G&ESDh4H!zG-oF)0hPP5l3;!fZK&fpf`+g)0zfW&?h+Dqs{oYf8y zF)%E|Kimz=s~AxD9g5%PPZd&-1cnHA2Rh;VaQ~z?y^8_cQo8t`r~NQG0z%L2rOAUp zAyeJO$Rv9&+31puz7H)v^2t6kN;Q7#aVk)15P692CX6gsHc@5BEJqeo7^BVdy&!|68OpOmpp%N6k`*dy-xFQ=C*PlgJ6vbIl uRcA$`)oBg>`&4If;$VIv{RBquZ4L1paF0*#LtgP^oWsY=c#6IdlCJ>p)(|BC literal 0 HcmV?d00001 diff --git a/Array/ArrayProbs.java/array_prob29.java b/Array/ArrayProbs.java/array_prob29.java new file mode 100644 index 0000000..5d16e07 --- /dev/null +++ b/Array/ArrayProbs.java/array_prob29.java @@ -0,0 +1,90 @@ + +public class array_prob29 { + // Minimum swaps required to bring all elements less than or equal to k together + private static int minSwap(int[] arr, int n, int k) { + int snowBall = 0; + int count = 0; + for (int i = 0; i < n; i++) { + if (arr[i] > k) { + snowBall++; + } else if (snowBall > 0) { + int temp = arr[i]; + arr[i] = arr[i - snowBall]; + arr[i - snowBall] = arr[i]; + count++; + } + } + return count; + } + + // arrange even before odd + private static void segregateEvenBeforeOdd(int arr[], int n) { + int i = -1, j = 0; + for (j = 0; j < n; j++) { + if (arr[j] % 2 == 0) { + i++; + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + for (Integer k : arr) { + System.out.println(k); + } + } + + // segregate 0 and 1 + public static void segeregateO1_A(int arr[], int n) { + + int count = 0; // counts the no of zeros in arr + + for (int i = 0; i < n; i++) { + if (arr[i] == 0) + count++; + } + + // loop fills the arr with 0 until count + for (int i = 0; i < count; i++) + arr[i] = 0; + + // loop fills remaining arr space with 1 + for (int i = count; i < n; i++) + arr[i] = 1; + + for (Integer k : arr) { + System.out.print(k + ' '); + } + } + + public static void segeregateO1_b(int arr[], int n) { + int l = 0, r = n - 1; + while (l < r) { + while (arr[l] == 0 && l < r) { + l++; + } + + while (arr[r] == 1 && l < r) { + r--; + } + if (l < r) { + int temp = arr[l]; + arr[l] = arr[r]; + arr[r] = arr[l]; + l++; + r--; + } + } + } + + public static void main(String[] args) { + + // int arr[] = { 1, 3, 2, 4, 7, + // 6, 9, 10 }; + // int n = arr.length; + // segregateEvenBeforeOdd(arr, n); + int arr[] = new int[] { 0, 1, 0, 1, 1, 1 }; + int n = arr.length; + segeregateO1_A(arr, n); + + } +} diff --git a/Array/ArrayProbs.java/array_prob3.class b/Array/ArrayProbs.java/array_prob3.class index f451654cdd56f7cfe2ff5f6bae4c31589864310d..662f63c247daa7e35df0de429605476f10021128 100644 GIT binary patch delta 84 zcmey#@t0%6Yi6@d1{MY;1_lO40nR;Kk<0@B{3BUd{3BTf{`yCYxd6g_V|GtZt3i5)O)V$%{@QfJcG&_Dv1gwIecr3|XuASi94hN_Smw= zwArKnhOSE0O*h@Ni(s_~bzSubRNb)SCv-s(aNd{@^P!RMeec|lckj7({(AEJeE^HN zY$1&)i9;4NOj&pj?<;ZGLJHFg`#_0;#Ee253uBl~;X}-+Q_(^RM z7DyCk)&%qmt*?B6vDF~-uk@N5e&;i9qd`RPe&e+TWMREhsVL86GYG51y3C=#nTo)k zYUI^#e&V&`Ac=X#HN7Ad*k4#*z2V*RN)0dEELEdU5N?)L8f)d-y5Ek1R@jv|#(TBZ z>(u>AfqFFKbvoYGm+ek#WBy1{#oNeWoQ618FA5r^%U<_uz9@0r#sU^?oWMyNr%<+W z8cQ~oac0Lqe!CJz{-)otaTe!nWU*i3yp0REXyYxsEwN(b5 zfVR$-_wM2^I@$4#>pQ1fAW0+jR(s36{we!sXUPGNDudo_b(qZ{q6m?(96%<$^XI{wU~zUF=wN^ zjj^9JSsQ0R`*4u79Hn05?JWCS#RObT;&bHCL>}Lf*Y9cjfu0l0b_m8(noWsGAtW@V zfk((ch9>^U7mvtHim`dVq^J(aVS;)koxEq&5^3M9=^5=mw`OES*{zuw?O(ShGvXh& zmdt23-CEkrh`*_bJ#bfN?=SrZdp6(4o^6c2I-qI(%LSZ-gNvADp@WrpheLXoXAK9R E0XInleE hm = new HashMap<>(); + int[] temp = Arrays.copyOfRange(arr, 0, N); + + Arrays.sort(temp); + + for (int i = 0; i < N; i++) { + hm.put(arr[i], i); + } + for (int i = 0; i < N; i++) { + if (arr[i] != temp[i]) { + count++; + int init = arr[i]; + swap(arr, i, hm.get(temp[i])); + hm.put(init, hm.get(temp[i])); + hm.put(temp[i], i); + } + } + return count; + } + + // Driver program to test the above function + public static void main(String[] args) + throws Exception { + int[] a = { 101, 758, 315, 730, 472, + 619, 460, 479 }; + int n = a.length; + // Output will be 5 + System.out.println(minSwaps(a, n)); + } +} diff --git a/Array/ArrayProbs.java/array_prob31.class b/Array/ArrayProbs.java/array_prob31.class new file mode 100644 index 0000000000000000000000000000000000000000..2a7d5b627421396d178f52953a9223f19857a336 GIT binary patch literal 900 zcmZuvO-~b16g{sqohhZrU}*t6W-5LT|-_(M!wnrKiw(^kR6&AWHbJNKS*-_O!ldOe6O))3-r!Ab^BqnRQ$8o-g?> zyG{oNqNPUDUA6B!foPxQy4LpcrrW4Y-OL627$WFWF&x7PMq}tjkBYGvF5;4k@fa@S zia_jam4J4tV^%ioRsRpv^qp#cHc;^B%WJs233Hyn#+jnhw&&Y5K2W1cLZWTkY2+8_ z*{5^cs!a>TTPpv;0_tW!s&ZgC!@d~f5>##mkRgImct-h^W)zHJ<2}S1CIa0&l@=(G z7DEs7fVzSZi-8g203o>`71OC#h#Tpg{sPKQNbE>r@8qk#PfDoOWVofMut;UY2pe^w zpRER%r`h-%nca|nA|k}O9|-fB&)QKtWLcoLEERO>6bwBlzr+oO)N5oJi~w27?LzNl z#daiY8hYB?JNZmgdnX^;4U)uld1V(W&;8cTmlU(VZYSvo=%d#Jw>k&|L%78s_AXMG zCO(T{JmB&lVH8i8FJZhjK^*EaLPDP61ji7fuRV#zlJ>jVok7N47T4%7j|tqyb<7|~ KvGc82;=ci= 1 && arr[i] <= n + && arr[i] != arr[arr[i] - 1]) { + + int temp = arr[arr[i] - 1]; + arr[arr[i] - 1] = arr[i]; + arr[i] = temp; + } + } + + for (int i = 0; i < n; i++) { + if (arr[i] != i + 1) { + return i + 1; + } + } + + return (n + 1); + } + + // Driver Code + public static void main(String[] args) { + int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }; + int n = arr.length; + int ans = firstMissingPositive2(arr, n); + + System.out.println(ans); + } + +} diff --git a/Array/ArrayProbs.java/array_prob32.java b/Array/ArrayProbs.java/array_prob32.java new file mode 100644 index 0000000..1ef53ca --- /dev/null +++ b/Array/ArrayProbs.java/array_prob32.java @@ -0,0 +1,92 @@ +package ArrayProbs.java; + +import DoubleLinkedList.rotate; + +//find peak element +/** + * Given an array of integers. Find a peak element in it. An array element is a + * peak if it is NOT smaller than its neighbours. For corner elements, we need + * to consider only one neighbour + * + */ + +public class array_prob32 { + // linear search + public int findPeak(int arr[]) { + + int n = arr.length; + if (n == 1) { + return 0; + } + + if (arr[0] >= arr[1]) { + return 0; + } + if (arr[n - 1] >= arr[n - 2]) { + return n - 1; + } + + for (int i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) { + return i; + } + } + return 0; + } + + // binary search iterative + static int findPeak2(int arr[], int n) { + int l = 0; + int r = n - 1; + int mid = 0; + while (l <= r) { + mid = (l + r) >> 1; + ; + if ((mid == 0 || arr[mid] >= arr[mid - 1]) && (mid == n - 1 || arr[mid] >= arr[mid + 1])) { + break; + } else if (mid > 0 && arr[mid - 1] > arr[mid]) { + r = mid - 1; + } else { + l = mid + 1; + } + } + + return mid; + } + + // recursive + static int findPeakUtil( + int arr[], int low, int high, int n) { + // Find index of middle element + // low + (high - low) / 2 + int mid = low + (high - low) / 2; + + // Compare middle element with its + // neighbours (if neighbours exist) + if ((mid == 0 || arr[mid - 1] <= arr[mid]) + && (mid == n - 1 || arr[mid + 1] <= arr[mid])) + return mid; + + // If middle element is not peak + // and its left neighbor is + // greater than it, then left half + // must have a peak element + else if (mid > 0 && arr[mid - 1] > arr[mid]) + return findPeakUtil(arr, low, (mid - 1), n); + + // If middle element is not peak + // and its right neighbor + // is greater than it, then right + // half must have a peak + // element + else + return findPeakUtil( + arr, (mid + 1), high, n); + } + + // A wrapper over recursive function + // findPeakUtil() + static int findPeak3(int arr[], int n) { + return findPeakUtil(arr, 0, n - 1, n); + } +} diff --git a/Array/ArrayProbs.java/array_prob33.class b/Array/ArrayProbs.java/array_prob33.class new file mode 100644 index 0000000000000000000000000000000000000000..7f3285f8f6f830cae293f3207670df2e6a55729f GIT binary patch literal 1132 zcmb_bO-~b16g{u=rqhmvw%{OOE24m<#X*CP@r#8Ym?~IJg#>GqDNJy%v`v|suyfJ4 zc4^#T)P#j>bfLx=Htviom;M$bo@q&_u5Fw5rsth|@44sQ`S$zsHh?oo>(J1n;{bZY z=tIAbAP(wCAgSSyh5>=#1-I;alLAU=bWT8Ct}HnM(P_8r+^nw_o!T9{SRxWytCZ@V zTPX{usX}%%E6|bm?8Qejc6FB$UUs}0XUVn636oREX35iVm}ysSmuOF_Fuh_ww#Q3$ zd3ikV)!g#(dB3cluheUc&XntyirclCz5bwDs}v_DOrIY?2w@F_5gfr$4MPzOVk0^QAof5QS=)hCtMvrJ`2=P*d)HC_oIK{FBNs`FoxyWp;- zKSI3YgTOwn!4}9hf)1`ewGO43;$&v~VnVIHz(7JRO=gm&B{NC6WLl~r4Rt{+SwSPX z#j~fM5b)2p7#wJ(9bsLty23roq#Z=NSfUS|bT&#?<2X*FvnAmdhJCHHxg|k7Z$<(? z6-z3X8nCp06-p)+)T(?5Tk#7gl2q^-w+)%tK-y4~8yHF((##mD`34=_8mcfip%ZLK zVOrWI4w3u{(KaNq%d@mbP;BnJHMFhv?6Zbuh5l=WO+zz6RKDlcUG&g}x-N9@4$2}_e);;#FZ#R^R~or# z&3_8z=4FhF8q;(0!Px%XOlEs>Y}=CWp=8FAhWrHi0qWiq_Oo%Iz(Kjk0ltqRJm9-# Nv+*KJ?dMql#vfV#zkUD! literal 0 HcmV?d00001 diff --git a/Array/ArrayProbs.java/array_prob33.java b/Array/ArrayProbs.java/array_prob33.java new file mode 100644 index 0000000..0227980 --- /dev/null +++ b/Array/ArrayProbs.java/array_prob33.java @@ -0,0 +1,100 @@ + +import java.util.*; + +//median of 2 sorted array; +public class array_prob33 { + // method1 + public int solution(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]; + } + } + + // Time Complexity: O((n+m) Log (n+m)) + + // 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]; + + // System.arraycopy(arr1, 0, arr3, 0, i); + // System.arraycopy(arr2, 0, arr3, i, j); + // Arrays.sort(arr3); + // System.out.print("Median = " + solution(arr3)); + + // } + + // method 2 : merge in efficient way and calculate + static int getMedian(int arr1[], int arr2[], + int n, int m) { + int i = 0; + int j = 0; + int count; + int m1 = -1; + int m2 = -1; + + if ((m + n) % 2 == 1) { + for (count = 0; count <= (n + m) / 2; count++) { + if (i != n && j != m) { + m1 = (arr1[i] > arr2[j]) ? arr2[j++] : arr1[i++]; + } + + else if (i < n) { + m1 = arr1[i++]; + } + + else { + m1 = arr2[j++]; + } + + } + return m1; + } else { + for (count = 0; count <= (n + m) / 2; count++) { + m2 = m1; + if (i != n && j != m) { + m1 = (arr1[i] > arr2[j]) ? arr2[j++] : arr1[i++]; + } + + else if (i < n) { + m1 = arr1[i++]; + } + + else { + m1 = arr2[j++]; + } + } + + return (m1 + m2) / 2; + + } + + } + + // Driver code + public static void main(String[] args) { + int ar1[] = { 900 }; + int ar2[] = { 5, 8, 10, 20 }; + + int n1 = ar1.length; + int n2 = ar2.length; + + System.out.println(getMedian(ar1, ar2, n1, n2)); + } + +} diff --git a/Array/ArrayProbs.java/array_prob34.class b/Array/ArrayProbs.java/array_prob34.class new file mode 100644 index 0000000000000000000000000000000000000000..c29019a0aa6cc5f36fd514244d6d68431d0f25a1 GIT binary patch literal 1280 zcma)6OHUI~6#i~I?bu-`AQt5%q9T1k5ko>kQmsi*11xl)0~u(iWI83mwZFoZ zapP88@K8eH)}LgI`rT>OQdyWu=H7eeJLi1oJLk^VAD>PD+{QxbB*UsvdV2;wuY@?54S6W~!cD%w+9~X9z^{_J(76RhJOs49IkoOZ{9l zosGaJPywp6dfbX{}z#kN~sotPYz+UaORJH>3&(b=*J zQcWEfaY@BZ9b*`mzzH3bxTRuBXVdTKxQlx#3?0+BucH$eRLtmjfLQ^(F_A#KAKs^y zTivwQJb`Fq#tIEe#ePMK?Eiv5cf3J@xpJ{cAG_@M6$Q;gK_FH~Gz2vg%PjG4s(L#) zG&^RoYUS3YOuuL5RKq!cu2m}UFn{bcqDGg~&`?5tx8hkPQY}}>J62nlvSVi!@C<{z8d2UVKmjiR+WGF_sh_Lh8cH5O>~SM-p6{@4j3OfS z=XI0NS-J+f_I*ZR=>WlO^5j@~luXr+=|d=~4}T(@CmQrS$9S!b(!)40S_0^TCMTdC zb)UEp?PmH2A%Wz{TXgy%(+3D2K@H&fUT{i@Dan&}m>G#F6K^oaMOjQIW6J0u&ecH4 zRC3t%&zOzsTYOesSZ_x$i~`N%f$YPd|omng5Lej^q`N+92ln zQ+bMOSmw8v7$zFTE4|+l5XLt$uGP{*g?iCPwWLA@YYA}e4IgVuK_$1OgmO!va4!21 cTIvuj`_TVN9QDN res, + int[] nums, int l, int h) { + // Base case + // Add the array to result and return + if (l == h) { + res.add(Arrays.copyOf(nums, nums.length)); + return; + } + + // Permutations made + for (int i = l; i <= h; i++) { + // Swapping + swap(nums, l, i); + + // Calling permutations for + // next greater value of l + permutations(res, nums, l + 1, h); + + // Backtracking + swap(nums, l, i); + } + } + + // ============== + + public static List> permute(int[] nums) { + List> res = new LinkedList<>(); + boolean[] visited = new boolean[nums.length]; + dfs(nums, res, new LinkedList<>(), visited); + return res; + } + + private static void dfs(int[] nums, List> res, List curr, boolean[] visited) { + // stopping codn; + if (curr.size() == nums.length) { + res.add(new LinkedList(curr)); + return; + } + for (int i = 0; i < nums.length; i++) { + if (!visited[i]) { + visited[i] = true; + curr.add(nums[i]); + dfs(nums, res, curr, visited); + curr.remove(curr.size() - 1); + visited[i] = false; + } + } + + } + + // O(n!). + + // ============= + /** + * + * Given a collection of numbers that might contain duplicates, return all + * possible unique permutations. + * + * For example, [1,1,2] have the following unique permutations: [1,1,2], + * [1,2,1], and [2,1,1]. + * + */ + + public List> permuteUnique(int[] nums) { + List> res = new LinkedList<>(); + if (nums == null || nums.length == 0) { + return res; + } + Arrays.sort(nums); + boolean[] visited = new boolean[nums.length]; + dfs2(nums, visited, new LinkedList(), res); + return res; + } + + private void dfs2(int[] nums, boolean[] visited, List curr, List> res) { + if (curr.size() == nums.length) { + res.add(new LinkedList(curr)); + return; + } + for (int i = 0; i < nums.length; i++) { + if (visited[i] == true) { + continue; + } + if (i == 0 || nums[i] != nums[i - 1] || (nums[i] == nums[i - 1] && visited[i - 1] == true)) { + visited[i] = true; + curr.add(nums[i]); + dfs2(nums, visited, curr, res); + curr.remove(curr.size() - 1); + visited[i] = false; + } + } + } + + public static void main(String[] args) { + + int arr[] = { 1, 2, 3 }; + System.out.println(permute(arr)); + } +} diff --git a/Array/ArrayProbs.java/array_prob35.java b/Array/ArrayProbs.java/array_prob35.java new file mode 100644 index 0000000..414a9c0 --- /dev/null +++ b/Array/ArrayProbs.java/array_prob35.java @@ -0,0 +1,29 @@ +package ArrayProbs.java; + +/** + * + * Given an array of non-negative integers, you are initially positioned at the + * first index of the array. + * + * Each element in the array represents your maximum jump length at that + * position. + * + * Determine if you are able to reach the last index. + * + * For example: A = [2,3,1,1,4], return true. + * + * A = [3,2,1,0,4], return false. + * + */ +public class array_prob35 { + public boolean canJump(int[] nums) { + int max = 0; + for (int i = 0; i < nums.length; i++) { + if (i > max) { + return false; + } + max = Math.max(max, i + nums[i]); + } + return true; + } +} diff --git a/Array/ArrayProbs.java/array_prob6.java b/Array/ArrayProbs.java/array_prob6.java index 2e21cb9..c0e82d8 100644 --- a/Array/ArrayProbs.java/array_prob6.java +++ b/Array/ArrayProbs.java/array_prob6.java @@ -8,12 +8,14 @@ public static int searchSortedAndRotated(int arr[], int n, int left, int right, return mid; } + if (arr[left] <= arr[mid]) { if (key >= arr[left] && key <= arr[mid]) { return searchSortedAndRotated(arr, n, left, mid - 1, key); } return searchSortedAndRotated(arr, n, mid + 1, right, key); } + if (key >= arr[mid] && key <= arr[right]) { return searchSortedAndRotated(arr, n, mid + 1, right, key); } @@ -21,6 +23,12 @@ public static int searchSortedAndRotated(int arr[], int n, int left, int right, return searchSortedAndRotated(arr, n, left, mid - 1, key); } + //time : logn + // space: 1 + + // 4, 5, 6, 7, 8, 9, 1, 2, 3 + // 0, 1, 2, 3, 4, 5, 6, 7, 8 + public static void main(String args[]) { int arr[] = { 4, 5, 6, 7, 8, 9, 1, 2, 3 }; int n = arr.length; diff --git a/Array/ArrayProbs.java/array_prob7.java b/Array/ArrayProbs.java/array_prob7.java index d25ee05..c7b8fe2 100644 --- a/Array/ArrayProbs.java/array_prob7.java +++ b/Array/ArrayProbs.java/array_prob7.java @@ -7,6 +7,22 @@ public class array_prob7 { + + //brute force + /** + * In this approach, we find out every possible permutation of list formed by the elements + * of the given array and find out the permutation which is just larger than the given one. + * But this one will be a very naive approach, since it requires us to find out every possible + * permutation which will take really long time and the implementation is complex. + * Thus, this approach is not acceptable at all. Hence, we move on directly to the correct approach. + * + * Time complexity : O(n!). Total possible permutations is n!. +Space complexity : O(n). Since an array will be used to store the permutations. + */ + + // solution explanation + //https://leetcode.com/problems/next-permutation/solution/ + public void nextPermutation(int[] nums) { int i = nums.length - 2; while (i >= 0 && nums[i + 1] <= nums[i]) { @@ -37,6 +53,13 @@ private void swap(int[] nums, int i, int j) { nums[j] = temp; } + /** + *t ime complexity : O(n)O(n). In worst case, only two scans of the whole array are needed +Space complexity : O(1)O(1). No extra space is used. In place replacements are don + * + + */ + public static void main(String[] args) { array_prob7 ob = new array_prob7(); int[] arr = { 1, 2, 3, 6, 5, 4 }; diff --git a/Array/ArrayProbs.java/array_prob8.java b/Array/ArrayProbs.java/array_prob8.java index 8c161c4..92909b2 100644 --- a/Array/ArrayProbs.java/array_prob8.java +++ b/Array/ArrayProbs.java/array_prob8.java @@ -3,6 +3,16 @@ import java.util.*; public class array_prob8 { + + /** + * + * Method 1 (Use Sorting) + * Approach: + * + * Sort the input array. + * Traverse the array and check for missing and repeating. + * + */ public static void repetAndMissingUsingMapping(int arr[]) { Map numberMap = new HashMap<>(); int max = arr.length; @@ -21,6 +31,32 @@ public static void repetAndMissingUsingMapping(int arr[]) { } } + /** + * + * time = O(n) + * space = O(n) + */ + public static void repetAndMissingUsingConstantSpace(int arr[]) { + int n = arr.length; + System.out.print("The repeating element is "); + + for (int i = 0; i < n; i++) { + int abs = Math.abs(arr[i]); + if (arr[abs - 1] > 0) { + arr[abs - 1] = -arr[abs - 1]; + } else { + System.out.println(abs); + } + } + + System.out.print("and the missing element is "); + for (int i = 0; i < n; i++) { + if (arr[i] > 0) + System.out.println(i + 1); + } + + } + public static void repetAndMissingUsingBit(int arr[], int n) { int xor1; int set_bit_no; @@ -67,9 +103,9 @@ public static void repetAndMissingUsingBit(int arr[], int n) { y = y ^ i; } System.out.println(" The missing element is " - + y + "and the " + + x + "and the " + "repeating number is " - + x); + + y); } public static void main(String[] args) { diff --git a/Array/ArrayProbs.java/array_prob9.java b/Array/ArrayProbs.java/array_prob9.java index ecf37f6..19c9efc 100644 --- a/Array/ArrayProbs.java/array_prob9.java +++ b/Array/ArrayProbs.java/array_prob9.java @@ -12,8 +12,8 @@ public static int findMin(int arr[]) { int left = 0, right = arr.length - 1; if (arr[left] < arr[right]) { return arr[0]; - }; - + } + ; while (right >= left) { int mid = left + (right - left) / 2; @@ -25,10 +25,10 @@ public static int findMin(int arr[]) { return arr[mid]; } - if (arr[mid] > arr[0]) { - left = mid + 1; - } else { + if (arr[right] > arr[mid]) { right = mid - 1; + } else { + left = mid + 1; } } return -1; diff --git a/Array/exmp.class b/Array/exmp.class new file mode 100644 index 0000000000000000000000000000000000000000..c733dcdea956931d63f3999ce570f2045abc78ee GIT binary patch literal 1047 zcmZuw+fEZv6kUhTbb6U`DGmy>+%Ki0t%4M_h>C=y35rP##E_^{I+DS*)0C;oi%)(D zG2z7*eJF`0et_TLtG@xRGc^H=D7r%))!$Z*|ic#h||wR3MlAXfCO-M3Gy`gxk$@R(h-9L5c# zb~g5{cUHDy)%LPQui@18^0HW@=r$X>_PQfmh3ya3dPc_S=tEqGfdL&?aZRANlfC9P z{lNnBncFh%mWFv93!t%xoQ5SGcW_t7J>(@?)^Q&z5?&1rn=+vt@3`4#q~wv9ZB_FEAsSm&rAbnhm-6)c^Iwjme07;sp+HK? z*EU-A$#qiKy_DII!tCuJ4myc)f{FMtXmmE_t_E6Kl*-t-B? zR|0`6T!X$-ZcuMx8M?@;qVnHoCNeq2Oqj{crkOO9%}!dJA@IXgL|LR48f~7|zY-t0 zCq4OuQqC!foXQ%xprIy@Fl-uX#t0rE{z(yO(@+exg|6eXKN2gieM^EbOz-k%oIr>; z!kMB(I%511=*B3inxvQ`$w5Yh(RGTL5F$xq=$y_=CQ3S~Wa2ZX(`F*sLLjFQuuYkG zyWLs3w~x<$OP1}%Lu3ZlQOT^E+y?ngvGOe2%Z3W$X4rO^c3Zkv2+#*C{DATzuAU&c y@eP{ULa2ps8%0`(wvpaKtc|+4+Yz_jc9e|A$bTFonBWVZ#5`ZQ;6cjqM*adR8m+Pb literal 0 HcmV?d00001 diff --git a/Array/exmp.java b/Array/exmp.java index 49fb91f..0fd40bc 100644 --- a/Array/exmp.java +++ b/Array/exmp.java @@ -1,28 +1,38 @@ public class exmp { - void swap(int arr[],int a ,int b){ + void swap(int arr[], int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } - int partition(int arr[],int l,int r){ - int i = l-1; + int partition(int arr[], int l, int r) { + int i = l - 1; int j = l; - int pivot =arr[r]; - while(j < r && arr[j] < pivot){ + int pivot = arr[r]; + while (j < r && arr[j] < pivot) { i++; swap(arr, i, j); } - swap(arr, i+1, j); - return i+1; + swap(arr, i + 1, j); + return i + 1; } - void sort(int arr[],int l,int r){ - while(r > l){ - int position = partition(arr,l,r); - partition(arr,l,position-1); - partition(arr,position+1,r); + + void sort(int arr[], int l, int r) { + while (r > l) { + int position = partition(arr, l, r); + partition(arr, l, position - 1); + partition(arr, position + 1, r); } } + + public static void main(String[] args) { + Double ob = new Double("2.4"); + System.out.println(ob.intValue()); + System.out.println(ob.doubleValue()); + System.out.println(ob.floatValue()); + System.out.println(ob.byteValue()); + + } } diff --git a/Bit/bit_prob_4.class b/Bit/bit_prob_4.class index 50369fbb992148af52884e87b6ded6ed2ed5b1a4..9f8872afed0b57021ec1626b2d9a0c17d9f4db0a 100644 GIT binary patch delta 594 zcmYLHJ8u&~5dP-w_U?Q+ze0}SI1VAP<2#esV2l%9A%0LK5D6(#8mg192ngjY=Y&&{ zCWsPQM~NtCXwra0Kopb|5fy)dzW_}X9jxsTA;T&e9nblVq%V8mpf~4jwjG$=1HQ)`(cgEx0-ox$iZqV=aHaa0ecki`U zz0JXHV>OP1fs&2$m?xx~K@jeQJ-@r&3Acj#J4qc2CdxJ{xM1L-jVdnLsL4H-ZPc+S znI#)(j1GQns8?_`x=sBuA@Rt6;#VH~+Yc)1ez-+YyFs5I+;-b*6EwHwZ5p^H555^4 zkw=Z_Cw<=7K@QThma#{tV`s}D&9F{y>)WK>hv zC>8Cg#l2IUPeYtQp%a)iaSUyK7`oUIQ}M8DMM9rtOrf5VqubP4pW$g z%gDKQ1{8*z;_T9g?ojNvrKhs}Id^G)l2w+X1cVV)aUKn7(-XNEO1 We4zXXgzH$r4bJ5ln~bM;p8W?WiCDG( delta 321 zcmYL_Jx;?w5QV?By#rMm3WP*KNx>mF z19cQ3W@%Vy-kW*zG&9{z7Bk8S39ZS6`(f$Rr CFeH-z diff --git a/Bit/bit_prob_4.java b/Bit/bit_prob_4.java index 61d4be1..d200a9a 100644 --- a/Bit/bit_prob_4.java +++ b/Bit/bit_prob_4.java @@ -1,3 +1,5 @@ +import java.util.ArrayList; + // print all subset from 1 to n; public class bit_prob_4 { public static void subset(int arr[], int n) { @@ -44,4 +46,54 @@ public static void main(String[] args) { int arr[] = { 1, 2, 3, 4 }; subset(arr, 4); } + } + + // backtracking solution + +findSubsets(List> subset, ArrayList nums, ArrayList output, int index) + { + if(index == nums.size()){ + subset.add(output); + return; + } + findSubsets(subset, nums, new ArrayList<>(output), index + 1); + output.add(nums.get(index)); + findSubsets(subset, nums, new ArrayList<>(output), index + 1); + } + + public static void main(String[] args) { + +// Main List for storing all subsets +List> subset = new ArrayList<>(); + +// Input ArrayList +ArrayList input = new ArrayList<>();input.add(1);input.add(2);input.add(3); + +findSubsets(subset, input, new ArrayList<>(), 0); + + // Comparator is used so that all subset get + // sorted in ascending order of values + Collections.sort(subset, (o1, o2) -> { + int n = Math.min(o1.size(), o2.size()); + for (int i = 0; i < n; i++) { + if (o1.get(i) == o2.get(i)){ + continue; + }else{ + return o1.get(i) - o2.get(i); + } + } + return 1; + }); + + + // Printing Subset + for(int i = 0; i < subset.size(); i++){ + for(int j = 0; j < subset.get(i).size(); j++){ + System.out.print(subset.get(i).get(j) + " "); + } + System.out.println(); + } + + } +} \ No newline at end of file diff --git a/DP/index.txt b/DP/aindex.txt similarity index 100% rename from DP/index.txt rename to DP/aindex.txt diff --git a/DP/dp_prob10.class b/DP/dp_prob10.class index ed3d29b7bbb3d9f13a3f039e6286b37344de7dc5..3801f7cc265bac9e00c9bb82314e03c11f731c06 100644 GIT binary patch delta 111 zcmeC>>gC!nk&!itk%38X@-)UTjI5ixnZy_+MH%KXNHXkTkYc#ZAj@!@L4e^Q13$xa z2F1<0m}MBvRT(%K)EHzK)ENvIG#FeMG#Mfov>0+2v>6&0bQq>E=rXKe&|}yGl)b=U P$iT>;$iTqB#GnKKMY9yV delta 111 zcmV~$zX}0y007|ccPLpHxVmDv^Iw$B3wQ{t-9y-QgUDz$s#_!vp^PSz7w`bSFR$gb z>poQ0L9{-c!Y`DIT@;6;>8#}@_L6vO_^A8p6!%g)EK*gOwywFJrM{JcjiIfPqp^#L MhpDHTAVnnm15JVytN;K2 diff --git a/DP/dp_prob10.java b/DP/dp_prob10.java index 77430e1..b2f60f6 100644 --- a/DP/dp_prob10.java +++ b/DP/dp_prob10.java @@ -6,7 +6,7 @@ public boolean matchReg(char[] text, char[] pattern) { T[0][0] = true; // Deals with patterns like a* or a*b* or a*b*c* - for (int i = 1; i < T[0].length; i++) { + for (int i = 2; i < T[0].length; i++) { if (pattern[i - 1] == '*') { T[0][i] = T[0][i - 2]; } @@ -45,7 +45,7 @@ public static void main(String args[]) { System.out.println(rm.matchReg("abbbbccc".toCharArray(), ".*bcc*".toCharArray())); System.out.println(rm.matchReg("aaa".toCharArray(), "ab*a*c*a".toCharArray())); - System.out.println(rm.matchReg("aa".toCharArray(), "a*".toCharArray())); + System.out.println(rm.matchReg("ab".toCharArray(), ".*".toCharArray())); } } diff --git a/DP/dp_prob11.java b/DP/dp_prob11.java index a4be4d6..ef4f697 100644 --- a/DP/dp_prob11.java +++ b/DP/dp_prob11.java @@ -29,30 +29,31 @@ public int maxValue1(int price[]) { return max[price.length]; } - public int maxValBOtotmup(int price[], int len) { - int T[][] = new int[price.length + 1][len + 1]; - for (int i = 0; i < T[0].length; i++) { - T[0][i] = 0; - } - for (int i = 0; i < T.length; i++) { - T[i][0] = 0; - } - for (int i = 1; i <= price.length; i++) { - for (int j = 1; j <= len; j++) { - if (j - i >= 0) { - T[i][j] = Integer.max(T[i - 1][j], T[i][j - i] + price[i - 1]); + public static int cutRod(int prices[], int n) { + + int mat[][] = new int[n + 1][n + 1]; + for (int i = 0; i <= n; i++) { + for (int j = 0; j <= n; j++) { + if (i == 0 || j == 0) { + mat[i][j] = 0; } else { - T[i][j] = T[i - 1][j]; + if (i == 1) { + mat[i][j] = j * prices[i - 1]; + } else { + if (i > j) { + mat[i][j] = mat[i - 1][j]; + } else { + mat[i][j] = Math.max( + prices[i - 1] + + mat[i][j - i], + mat[i - 1][j]); + } + } } } } - for (int i = 0; i <= price.length; i++) { - for (int j = 0; j <= len; j++) { - System.out.print(T[i][j] + " "); - } - System.out.println(); - } - return T[price.length][len]; + + return mat[n][n]; } public static void main(String args[]) { diff --git a/DP/dp_prob15.class b/DP/dp_prob15.class index 8bc3fe2b2a9d338afc5577a41b53b26fb6ca30f7..08505a4b918428af24f6d06c965a1f55c5a5e33d 100644 GIT binary patch delta 798 zcmZuvOHUI~6#ni!I%OCtOqo%@p)VdSZKpho0v1J4fm#p~44PVOr0vZj4SQ=ic+3$NkQC?>pmr)2+|d$`OE3Eb1^3 z(h!!nYqhElA0iFtLbn$^I(iY+At7c`YErnaFexwkO)v~<7!m~`VTMIyL_>OSVVRBY zy}r}sM=L|igZx%LwU#dxQ!}N_Lb0%6paZ8hoH1|~V?4py8^;Yy;GBUBCV7e3{_|d3 zFffIS1}+JF0Cd@+~NK+<=*CXHLXUyii%3O0BMLMBX(W;@H zetxXj+oYCAqtI7ssL}c~9zRl6TVv(o)@z@Q!&X zqs>!615k#(tFryt7lO)Y6g@Jc-k^HtIU;e#O)CUgO2Sgy3YtWTw(SUSC9_{U{#|!a zr!PjCLNnP8=)};3L!$m%PskvL(Ax*hlhT&#&M delta 699 zcmYLHO>YuW6g_Vk7#Lq|3yj6$6liNHUxQSOXe%gIEwMHxCTd-1s1U>;LzvNRW8xoZ zW}|WA&ZVibH0h!%S1$Yy{R1Z5HUzwnO=n*2$GP{td+vSjWb6lj{AX}@1mHRy3Js<07UNT;;fiWd?22j9O;vz1=k1RmSCHpKso;EK zvn7U!vT53u-K};W)$KQC%^LUMh8H(ER{N^G=Fow8ctd_KFUxp7?9Nb%3$WOgP=c`4JCI?qU3FF4Hs_AW0pisKYc> h$xsagIb;dbN4#dRMp~sa%earbl(#sl$S9K``5%spbQ%Bv diff --git a/DP/dp_prob15.java b/DP/dp_prob15.java index a3c5091..18e73db 100644 --- a/DP/dp_prob15.java +++ b/DP/dp_prob15.java @@ -10,7 +10,7 @@ public int minimumCoinBottomUp(int total, int coins[]) { R[i] = -1; } for (int i = 0; i < coins.length; i++) { - for (int j = 1; j <= total; j++) { + for (int j = 1; j <= total; j++) { if (j >= coins[i]) { if (T[j] > 1 + T[j - coins[i]]) { T[j] = 1 + T[j - coins[i]]; @@ -23,24 +23,25 @@ public int minimumCoinBottomUp(int total, int coins[]) { return T[total]; } - - private void printCombinations(int R[], int coins[]) { if (R[R.length - 1] == -1) { System.out.println("No solutions possible"); return; } + for (Integer i : R) { + System.out.print(i + " "); + } + System.out.println(); int start = R.length - 1; System.out.println("Coins used to form total are : "); while (start != 0) { int j = R[start]; - System.out.print(coins[j] + " "); + System.out.println(j + " : " + coins[j]); + // System.out.print(coins[j] + " "); start -= coins[j]; } System.out.println(); } - - public static void main(String[] args) { int total = 13; diff --git a/DP/dp_prob18.class b/DP/dp_prob18.class index 2782261f567d0b0d4eb0ec5a1ef7c2d723e20ae5..06366e4c61cd9c1b783e0f8e30cb07e6fad3ecf1 100644 GIT binary patch delta 264 zcmX|+OG^S_6o#J}=X3lPZi-oCWCfbl*bLdAboaIj#8pVpBEn_hs#S|N{)5>FE?Ni; zK?@gRuA)B>{-J0*5(J0C`|@56XR1H-_`}q7l4#&P{4#T$o1$a6j#ZkV1X*2gMzXyG zW#y_1Ct#D=(Jy#I{y?v{}V-B)oGfA=jTieJM@;^h8{6}gi`ktfZLumbDs z3ftqDeVVvjQ{;gIdcq$?d*YC1N(?ySg@BRZH!7@2Q$XsMtWCzoG=A7J{BWL_`KR*G d8LOPL%>_P}va7VHaZ8;p4JmJ8kd+FP%>}4KE`R_4 delta 241 zcmdnTxs7wfb|y|M1~vvx1_p)|lMgVd1c&N~vS^F47;Rx-1+rLD^mZ_?`7@ibin5Bb zEMhR!7G(uWu|rgFEM|}bDgq)sxE5Bu1dxsvR>tN3&$X}s$yJlBnXTO27zBZKs4%cH zs50;}s4)mJXfQ}KXaad!43-Sq49*NX3?U4<4B0?-AyB-W!HA)n!I)tRg9*cI22+Ol zK=x7wi^&I=MVMt7^(J3u-l1;;bh#~qFoPX~B7;4HK7#|0<;dX6;KUFEG%tn0g(088 Om4T5#4rntIgFFD>Gb(ui diff --git a/DP/dp_prob20.java b/DP/dp_prob20.java index c6644b9..02a236c 100644 --- a/DP/dp_prob20.java +++ b/DP/dp_prob20.java @@ -1,6 +1,6 @@ // Longest Common String public class dp_prob20 { - public int longestCommonSubstring(char str1[], char str2[]) { + public int longestCommonString(char str1[], char str2[]) { int T[][] = new int[str1.length + 1][str2.length + 1]; int max = 0; diff --git a/DP/dp_prob22.java b/DP/dp_prob22.java index b5d428b..effe138 100644 --- a/DP/dp_prob22.java +++ b/DP/dp_prob22.java @@ -30,7 +30,9 @@ public boolean isMatch(String s, String p) { if (pattern[j - 1] == '?' || pattern[j - 1] == str[i - 1]) { T[i][j] = T[i - 1][j - 1]; } else if (pattern[j - 1] == '*') { - T[i][j] = T[i - 1][j] || T[i][j - 1]; + T[i][j] = T[i - 1][j] || T[i][j - 1]; //[i][j-1] - 0 occurence | [i-1][j] - 1 or more ocurrence ; + } else { + T[i][j] = false; } } } diff --git a/DP/dp_prob23.java b/DP/dp_prob23.java index b5eb93a..6e7ae66 100644 --- a/DP/dp_prob23.java +++ b/DP/dp_prob23.java @@ -19,7 +19,6 @@ public int minCost(int cost[][]) { for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { T[i][j] = cost[i][j] + Math.min(T[i - 1][j], T[i][j - 1]);// if only right and bottom move allow - } } path(T, cost, m - 1, n - 1); diff --git a/DP/dp_prob27.class b/DP/dp_prob27.class index 13764a9f96921bfbf7027bb48ca76f1b4fe90d12..c3551f9d00521fc192916cea970666512e47846f 100644 GIT binary patch delta 951 zcmYjPOHUI~6#j1KPNyvcmdEgD9o`fQwP1mQJPIPHHIQyJhG-(?5d$HGU@za041mk zK%!oW1_O;s*ZI+eW@WXMu`U`wJ35pbQ`RLV;$;ws8tB>@UZ^RaTUpQL?`EGox|3gA z7SP+$>1f)(<*nzVkqZc#s6>T{YSak$=T{%BuC2@_`V1sYbfd>a6)GGdDhGRgNSa)$ z-@p|U0~j<>u6`WAkcnXgeMkuem$Hwuoy*zW!_Lg?(!yL`z;iF{Oo(o61f$M|$X5v% zt80t7{Bn*tQE%X?>N?^45K(c%Y4E(2Hw9Xpl&8fx^E9U3bNZgjPl%7p3sP*b>CNnW9GkVGnZ6hADwTw(k zONMt4wxqoSD`wwk*pl<{narjXFVDVgYLuU1A%}YDRj6Smn)Uklet=@P*QQPezMlW)a`MsT5z;l0F^ zL?cfqK?3@Dj-wdFEezo{uX2uh5hGY(Y@N9cjJfpK@SbA8fIMf&N0$6#DSV6~MU=(^ fQ?qI@P8}c#W4MlMBrih0gqfmN2HW@m0-e7Bg$|4s delta 475 zcmYL`+b%Rg6otR)YO1@n!whDO!#E6se=yExB3!s3u3a$>k%%B7|E+igsdsSYhQtsO z4##$ z=yqX`LwQ5*)!P2m+hS)-bxb`8MYwmmb$WKPGdgAHi|OZIOalo!tWraTfPt7nh784+ zVMb!=NH{dAs5>nEFBOkU#|OoYox}azb9<@A^cdszL7fMN30FB|m%V;9XOFyle_qjJ z*LBve=t8{~>uyz`5HqsZ*h`&itd(4)MBvLV-M;_a=p|KaKXg$gZJVDq;`}>5=jSh6 zMU9LIX;Ev!kiiYFQHH?H;;52n#}fpm+24M|yAi1P>z5^@k<<@)Rq8!qU=U_7W)NjyWDo-CWMU8o04^mA3;+NC diff --git a/DP/dp_prob30.java b/DP/dp_prob30.java index 2214ec1..951b8ab 100644 --- a/DP/dp_prob30.java +++ b/DP/dp_prob30.java @@ -11,13 +11,10 @@ public int maxSum(int input[]) { return inclusive; } - - public static void main(String[] args) { dp_prob30 ob = new dp_prob30(); // int arr[] = { 2, 10, 13, 4, 2, 15, 10 }; - int arr[] = { 5, 5, 10, 100, - 10, 5 }; + int arr[] = { 2, 7, 9, 3, 1 }; System.out.println(ob.maxSum(arr)); } diff --git a/DP/dp_prob32.java b/DP/dp_prob32.java index f516e95..98a1c9f 100644 --- a/DP/dp_prob32.java +++ b/DP/dp_prob32.java @@ -1,5 +1,12 @@ // count the number of bst for n keys // hint use catalin number + +/** + * + * The first few Catalan numbers for n = 0, 1, 2, 3, … are 1, 1, 2, 5, 14, 42, + * 132, 429, 1430, 4862 + * + */ public class dp_prob32 { public int countTrees(int n) { int T[] = new int[n + 1]; diff --git a/DP/dp_prob33.class b/DP/dp_prob33.class index 28b996a3c7cc8e8768639ebbd5537c6681b432a0..b441b5dc4614a0373e56f22e12cb588a7c211a1d 100644 GIT binary patch delta 633 zcmYjPK~ED=5dL0w+qb)HEiHDzmRdlCwsc!CLTQc6Z{wa0rh);#(lf9GvAw;Z)VY+iLbF<%lPKuDNiB*RDM`%lHrK|>0@fgS+zW&52Gv4qjjMQX z_jU8(2_yuPTkWUq>UO)gS#9;g?q)Y|;bC0DcTquA;=GFs+HrKX-w$`fpgp+V4IlM8 zJBb)-7V0i8;*yKYSP-x~gY`kse^4iy!kCU+RLi2JzKe;tJS=0o=U@p})Jw6Xeu}BM zSzt914V~tiN=Ay}x@tr|iB)wFxix09dHt9WV7Zi|>W<+}CyB*q0R|H1LPmAW^_f|Gz#N7s;3Ux+oZnQWge{RidewoM zf5s@z3`f8=k{Dr delta 547 zcmXAlO=}ZT6o#LfBy%T|(KbycHEOI)KhrdcH8!zUYY|)oS`Y<6ij>iYT8T+Whpzn# zi2)gUw}Gy9bB@Ci;>rY z<6PqMh&Wdr#>t0fLNV!JlMT&O$V@9{_U~^Pv-?M@{yEMYBwzY_ex>ENw=0cy(A;kJ z6a|+#iUz~?I-OuQ==t6CX7Hl3wL4@nZ&Pw9Q&C)VS>U=$HH;JA>TY&>ooCgmOOlb0 zy`i5PjhMqCHT}a_N~g|J?Q|*+dOPjlQP6Apue53AM^!f@T5W^qY@_g4Q4cdL>jkr5 z+|e86XJbVtBWo#J`VChE11VnYknTn@2`;W<&+uzZ63-A~$Z6g@xMQmrV=FPz9k#f^^&qBtMed>F<^g2M!HBQBc-8m&M}Xfg49f5hHq zwk3P7R8-hcn1mf zNtl3N#61y{49-WIu30M#TqwNFz^9Fh%HYmwy85(LFR9HfrBt(#veDA5RkdtXG<|P% zlPW_y=}b7o(4V)Ia&<##w5cKj)TXXzI>TsaCwrhAD)E}4@5S?0lS)(e7%6YGnq_rO zvs({T8m}5nqm)d4b|E=DyG|sU=LWL?M&l zv~542nE}S&tt(YEZRlmidZtt7w z#GGv~!4SMMqv?l6RlQthN5q;^wv6VHh(-D;S;MHd8Vs(CuB**-O)*WCl)dSmaM`1? z%XLMs)KoLrDNNlI(uG_r+&XHgx6r#kd1v#f?wwq=NGr8kUbEDch$O@84S%<3W4QN! z9;WD!i*&{T4$MABbeHJKPmxg+B45EiQNqwicV`=P5|K_B&Pp*+QXAHRDhZO9y- zlX*TD;gX*DV+h=du;TZ<$GYt2auGjYA@~FOWWP*#j1Ym4#9Mef*}^f#I;`b)7?Axh zVlpveySdjK`}pU(?2DbyEJs_-L(%}soTNsge1NV|xG{!1n8YAvFpN3+DKEi`JfSZM zufRtv&|BvP#zeR;z}UE7`UQc^dx+6-^_)C$#FND{p~!g>g(B}+C=> '0') + count[i] = count[i - 1]; + + if (digits[i - 2] == '1' || digits[i - 2] == '2' && digits[i - 1] < '7') { + count[i] += count[i - 2]; + } + } + return count[n]; + } + + // Driver Code + public static void main(String[] args) { + char digits[] = { '1', '2', '3', '4' }; + int n = digits.length; + System.out.println("Count is " + + countDecodingDP(digits, n)); + } +} diff --git a/DP/dp_prob42.java b/DP/dp_prob42.java new file mode 100644 index 0000000..7b55be1 --- /dev/null +++ b/DP/dp_prob42.java @@ -0,0 +1,45 @@ +/** + * longest repeating subsequence + * + * Input: str = "abc" + * Output: 0 + * There is no repeating subsequence + * + * Input: str = "aab" + * Output: 1 + * The two subsequence are 'a'(first) and 'a'(second). + * Note that 'b' cannot be considered as part of subsequence + * as it would be at same index in both. + * + * Input: str = "aabb" + * Output: 2 + * + * Input: str = "axxxy" + * Output: 2 + * + * + */ + +public class dp_prob42 { + // Function to find the longest repeating subsequence + static int findLongestRepeatingSubSeq(String str) { + int n = str.length(); + + // Create and initialize DP table + int[][] dp = new int[n + 1][n + 1]; + + // Fill dp table (similar to LCS loops) + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + // If characters match and indexes are not same + if (str.charAt(i - 1) == str.charAt(j - 1) && i != j) + dp[i][j] = 1 + dp[i - 1][j - 1]; + + // If characters do not match + else + dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); + } + } + return dp[n][n]; + } +} diff --git a/DP/dp_prob43.java b/DP/dp_prob43.java new file mode 100644 index 0000000..20d831a --- /dev/null +++ b/DP/dp_prob43.java @@ -0,0 +1,50 @@ +public class dp_prob43 { + static int collectGold(int[][] gold, int x, int y, + int n, int m, int[][] dp) { + + // Base condition. + if ((x < 0) || (x == n) || (y == m)) { + return 0; + } + + if (dp[x][y] != -1) { + return dp[x][y]; + } + int rightUpperDiagonal = collectGold(gold, x - 1, y + 1, n, m, dp); + // right + int right = collectGold(gold, x, y + 1, n, m, dp); + // Lower right diagonal + int rightLowerDiagonal = collectGold(gold, x + 1, y + 1, n, m, dp); + + // Return the maximum and store the value + return gold[x][y] + + Math.max(Math.max(rightUpperDiagonal, + rightLowerDiagonal), + right); + } + + static int getMaxGold(int[][] gold, int n, int m) { + int maxGold = 0; + int[][] dp = new int[n][m]; + for (int row = 0; row < n; row++) { + Arrays.fill(dp[row], -1); + } + for (int i = 0; i < n; i++) { + + // Recursive function call for ith row. + int goldCollected = collectGold(gold, i, 0, n, m, dp); + maxGold = Math.max(maxGold, goldCollected); + } + + return maxGold; + } + + public static void main(String[] args) { + int[][] gold = { { 1, 3, 1, 5 }, + { 2, 2, 4, 1 }, + { 5, 0, 2, 3 }, + { 0, 6, 1, 2 } }; + int m = 4, n = 4; + System.out.println(getMaxGold(gold, n, m)); + } +} diff --git a/DP/dp_prob44.class b/DP/dp_prob44.class new file mode 100644 index 0000000000000000000000000000000000000000..ae2e8b7b67517dd543ad74a4c81d8ae333e6018e GIT binary patch literal 1075 zcmY*Y+fEZv6kTWL%uG8SXax(F3JL=D0wqDBi4Y?(nlvdLlOjpeM3|OJioK;26Q1?O zC!;@L!V3@jq9jTP`T>5Ci3z$+Te)=RT=v>)?X&kj(_g2@KLOlB%7%^We)utJa~iX7 z!;hO7SH^^mTbNY7DGSpUZVULb&sNqm>Fi?xkroIjGq<|Dns&1S=2E3zX+IFqWAQZs z`KYm376@i4^>TK%RxGzxy<(M!UaQmvj95AyXN|ok zv(+drETojqK|g{H`rtSiz@UIuNLz?Gh$G=3j3En22Q!#;5P&1#Ka&fD&JT8r+vQUG z5|rE9X_sp(vaw4?xSM6AG53@ywwY+zt1Su)c4AzH1+1nbRau{mrQ>TDXX|ZVlLntk zgFBx}nX3Vogdpb-tx>K*p^5JhU$_yt!rAPA?1?Iodqqt#n8r0Q65WS2asV0qOjElc zFmaWL0nPtVY1xdP_BSJ1bba~??Zmz>yNeN#dP1MqQ!{#M!;KhvLMlVjkax|nN!C8r zBQk8NAvaSbht1SR&q~UU)dP>9GX$v|irRJlr*?%sP*LBQ;^6Pch{}ZQStbxMdV8Kv z#(8bi>?PPui=FJ}6J_^eY{?x~{+tbZ%l$hHcWMtpJ4MohRGemsF zQ1Mk18FJig*Ba=G)eRWQnc0Xug82>B`OOb?G91G^|H>~gf!CPCdrb2-BWEAY6zfqx Zzi|kkbqMWTZg)Nr4H7y@BP3~v{sX4qu?zqJ literal 0 HcmV?d00001 diff --git a/DP/dp_prob44.java b/DP/dp_prob44.java new file mode 100644 index 0000000..0ff193b --- /dev/null +++ b/DP/dp_prob44.java @@ -0,0 +1,58 @@ +/** + * + * A car factory has two assembly lines, each with n stations. A station is + * denoted by Si,j where i is either 1 or 2 and indicates the assembly line the + * station is on, and j indicates the number of the station. The time taken per + * station is denoted by ai,j. Each station is dedicated to some sort of work + * like engine fitting, body fitting, painting, and so on. So, a car chassis + * must pass through each of the n stations in order before exiting the factory. + * The parallel stations of the two assembly lines perform the same task. After + * it passes through station Si,j, it will continue to station Si,j+1 unless it + * decides to transfer to the other line. Continuing on the same line incurs no + * extra cost, but transferring from line i at station j – 1 to station j on the + * other line takes time ti,j. Each assembly line takes an entry time ei and + * exit time xi which may be different for the two lines. Give an algorithm for + * computing the minimum time it will take to build a car chassis. + * + */ + +public class dp_prob44 { + static int NUM_LINE = 2; + static int NUM_STATION = 4; + + static int min(int a, int b) { + return a < b ? a : b; + } + + static int carAssembly(int a[][], int t[][], int e[], int x[]) { + int T1[] = new int[NUM_STATION]; + int T2[] = new int[NUM_STATION]; + int i; + + T1[0] = a[0][0] + e[0]; + T2[0] = a[1][0] + e[1]; + for (i = 1; i < NUM_STATION; ++i) { + T1[i] = min(T1[i - 1] + a[0][i], T1[i - 1] + t[1][i] + a[0][i]); + T2[i] = min(T2[i - 1] + a[1][i], + T1[i - 1] + t[0][i] + a[1][i]); + } + + // Consider exit times and return minimum + return min(T1[NUM_STATION - 1] + x[0], + T2[NUM_STATION - 1] + x[1]); + + } + + // Driver code + public static void main(String[] args) { + int a[][] = { { 4, 5, 3, 2 }, + { 2, 10, 1, 4 } }; + int t[][] = { { 0, 7, 4, 5 }, + { 0, 9, 2, 8 } }; + int e[] = { 10, 12 }, x[] = { 18, 7 }; + + System.out.println(carAssembly(a, t, e, x)); + + } + +} diff --git a/GPP/abhyas.java b/GPP/abhyas.java deleted file mode 100644 index 2a1b1ec..0000000 --- a/GPP/abhyas.java +++ /dev/null @@ -1,101 +0,0 @@ -import java.util.Arrays; - -class abhyas { - public static void SOE(int n) { - int prime[] = new int[100]; - Arrays.fill(prime, 0); - - for (int i = 2; i <= n; i++) { - if (prime[i] == 0) { - for (int j = i * i; j <= n; j += i) { - prime[j] = i; - } - } - } - - for (int i = 2; i <= n; i++) { - if (prime[i] == 0) { - System.out.println(i); - } - } - } - - public static void pf(int n) { - int spf[] = new int[100]; - Arrays.fill(spf, 0); - - for (int i = 0; i <= n; i++) { - spf[i] = i; - } - - for (int i = 2; i <= n; i++) { - if (spf[i] == i) { - for (int j = i * i; j <= n; j += i) { - if (spf[j] == j) { - spf[j] = i; - } - } - } - } - - while (n != 1) { - System.out.println(spf[n]); - n = n / spf[n]; - } - } - - public static void toh(int n, char src, char dest, char help) { - if (n == 0) { - return; - } - toh(n - 1, src, help, dest); - System.out.println("move from " + src + " to " + dest); - toh(n - 1, help, dest, src); - } - - public static int countPath(int s, int e) { - if (s == e) { - return 1; - } - if (s > e) { - return 0; - } - int count = 0; - for (int i = 1; i <= 6; i++) { - count += countPath(s + i, e); - } - return count; - } - - public static boolean isSafe(int arr[][], int x, int y, int n) { - if (x < n && y < n && (arr[x][y] != 1)) { - return true; - } - return false; - } - - public static boolean ratInMaze(int arr[][], int x, int y, int n, int sol[][]) { - // base case - if (x == n - 1 && y == n - 1) { - return true; - } - - if (isSafe(arr, x, y, n)) { - sol[x][y] = 1; - if (ratInMaze(arr, x + 1, y, n, sol)) { - return true; - } - if (ratInMaze(arr, x, y + 1, n, sol)) { - return true; - } - sol[x][y] = 0; - return false; - } - - return false; - } - - public static void main(String[] args) { - pf(45); - } -} \ No newline at end of file diff --git a/Graph/prob11_graph$Edge.class b/Graph/prob11_graph$Edge.class index 5cb61ff6245a33a7c813e1d37597430bfc093dd9..16cf9c5bbf3c81dcfc01b94400369751ea141f9d 100644 GIT binary patch delta 21 ccmX@ae296&bVg1Q22KW11_=hS$qN{j06Y!^k^lez delta 21 ccmX@ae296&bVg2522KVs1_=i7$qN{j06ZxKl>h($ diff --git a/Graph/prob11_graph.class b/Graph/prob11_graph.class index 24c384125383bf0e8ad24fb30aa280aac9d1babb..ce03a972879cb7bd75616215ee702f1e58a6b2c9 100644 GIT binary patch delta 329 zcmWNNODM!~5XV2iZP$N2Vy#ljdbHXHt3~n(<>aj-t1XZG6*iPdD3AU`X;0GTP)aS8)G4Z`Nxqd}=ErT9 zhwu`njEFR08i;07o``W`6w{24I90Sr9w$Vb8arsGlYY7wp_>Ff*z|HlA8F+;RljDC zTZXu2m?x=T7$wgb?~L=I+9#8IGbIc(tLTpkEDOKP7-JDK@JrTbO&BMEiy1s5#WyRE zIfBd!Yf-Cg23XSQWu{qSfmKqhvBNsYY;eIQS8Q>^Hh1juz#h-+3+8}V4#^4m4TmpI YwC&UsaArz4*SDg=a?z+$$>hDUf63K4SpWb4 delta 329 zcmWNNO(;ZR6o#K~y5o+Y7*{Ea%U~Ka!-%Ny6J_Uj7V?)u4aF1+g+hZ!cO^|$7FJdk z)GTCeZ$FFKVWljTg$-}tsZ;NHzjK~*JjZh$3zq9*QBNriR1%_=MqHX`RqiC5`?1p1 zEd+>CMNGaZVdD9WKWefG%4sJ^2X(TBlp}QMW0G!q7^Ig``k0}gGy@z;@uXj>e$6nq zjBqc<6JxwEPLT=TN%5iDCzE_LB?Q!~?2j638%JS`v56S?B_Fg?COeCdIsD9vZ$Ti7 zG_yoPBaOQjNUpsY;eRT7i@9GHaAl4*yVvep4k`70k6U>$o0lCUz}*# WsVU*iRB*0q#f0S}u2snu18x8IcRHK^ diff --git a/Graph/prob11_graph.java b/Graph/prob11_graph.java index ecc6713..3ebe65e 100644 --- a/Graph/prob11_graph.java +++ b/Graph/prob11_graph.java @@ -11,7 +11,6 @@ * Dijkstra and suites well for distributed systems. But time complexity of * Bellman-Ford is O(VE), which is more than Dijkstra. * - * */ public class prob11_graph { diff --git a/Graph/prob13_graph.class b/Graph/prob13_graph.class index 45cfd007a03435682245e4c6f974c9f59b14edee..f27a04a0893158805daf87152d46772734b2d422 100644 GIT binary patch delta 138 zcmbQwKc9cYcVFqXqqsHF_{i~$V3jNuG^jPVTqjOh#kj71EA kjI|6wjQv1*Dnl^iY@paehS16K?7^)146FFqXtFbiF>o-5GjK5|FmN*{GVm~HFz_LYp~-t$LIp(`KiHNXfTZMRW!B4#nzD=m3<`|l42q2L3`&gY49bi}3@VJZ i462O%Kzb^J8sluB*g^)4$@1*MtV|5749t_u*);&{&lM>E diff --git a/Graph/prob13_graph.java b/Graph/prob13_graph.java index 6fba0e5..1a05270 100644 --- a/Graph/prob13_graph.java +++ b/Graph/prob13_graph.java @@ -8,7 +8,7 @@ * * Given a 2D screen, location of a pixel in the screen and a color, replace * color of the given pixel and all adjacent same colored pixels with the given - * color + * color * * Input: * screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1}, @@ -62,6 +62,7 @@ static void floddFillUitl(int screen[][], int x, int y, int prevC, int newC) { floddFillUitl(screen, x + xP[i], y + yP[i], prevC, newC); } + static void floodFill(int[][] screen, int x, int y, int newC) { int currC = screen[x][y]; if (currC == newC) diff --git a/Graph/prob16_graph.class b/Graph/prob16_graph.class index f8a1d6af0023ce41c28bd9cb0d90aae7259b90e8..69f4d39a09db821bfa1098475fa0fdf1661e1e35 100644 GIT binary patch delta 21 ccmX@ccZ_d?C_85`LpnnULmoruWI1*X074%HF8}}l delta 21 ccmX@ccZ_d?C_AS&Lpp;GLmq?gWI1*X06|9u7XSbN diff --git a/Graph/prob16_graph.java b/Graph/prob16_graph.java index c99e6b0..9f12ba4 100644 --- a/Graph/prob16_graph.java +++ b/Graph/prob16_graph.java @@ -21,7 +21,7 @@ boolean graphColoringUtil(int graph[][], int m, int color[], int v) { for (int c = 1; c <= m; c++) { if (isSafe(v, graph, color, c)) { color[v] = c; - if (graphColoringUtil(graph, m, color, v + 1)) { + if (graphColoringUtil(graph, m, color, v + 1 )) { return true; } color[v] = 0; @@ -30,8 +30,6 @@ boolean graphColoringUtil(int graph[][], int m, int color[], int v) { return false; } - - boolean graphColoring(int graph[][], int m) { color = new int[V]; for (int i = 0; i < V; i++) @@ -74,7 +72,16 @@ public static void main(String args[]) { { 1, 1, 0, 1 }, { 1, 0, 1, 0 }, }; + + // for (int i = 0; i < n - 1; i++) { + // int j = i + 1; + // if (A[i] != B[j] && i != j) { + // int index = select(A); + // cost += B[index]; + // } + // } int m = 3; // Number of colors Coloring.graphColoring(graph, m); } + } diff --git a/Graph/prob17_graph.java b/Graph/prob17_graph.java index 70786eb..092b7d0 100644 --- a/Graph/prob17_graph.java +++ b/Graph/prob17_graph.java @@ -1,11 +1,14 @@ import java.util.*; public class prob17_graph { + static class qentry { int v;// Vertex number int dist;// Distance of this vertex from source } + + public static void main(String[] args) { int N = 30; int moves[] = new int[N]; @@ -45,7 +48,7 @@ static int getMinDiceThrows(int move[], int n) { for (int j = v + 1; j <= (v + 6) && j < n; ++j) { if (visited[j] == 0) { qentry a = new qentry(); - a.dist = (qe.dist + 1); + a.dist = (qe.dist + 1); visited[j] = 1; if (move[j] != -1) { a.v = move[j]; @@ -59,4 +62,5 @@ static int getMinDiceThrows(int move[], int n) { return qe.dist; } + } diff --git a/Graph/prob20_graph.java b/Graph/prob20_graph.java index 80da87e..b2f83de 100644 --- a/Graph/prob20_graph.java +++ b/Graph/prob20_graph.java @@ -16,7 +16,7 @@ boolean isSafe(int M[][], int row, int col, boolean visited[][]) { // row number is in range, column number is in range // and value is 1 and not yet visited - return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]); + return (row >= 0) && (row < ROW) && (col >= `0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]); } void DFS(int M[][], int row, int col, boolean visited[][]) { @@ -24,14 +24,14 @@ void DFS(int M[][], int row, int col, boolean visited[][]) { // of 8 neighbors of a given cell int rowNbr[] = new int[] { -1, -1, -1, 0, 0, 1, 1, 1 }; int colNbr[] = new int[] { -1, 0, 1, -1, 1, -1, 0, 1 }; - + // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) - DFS(M, row + rowNbr[k], col + colNbr[k], visited); + DFS(M, row + rowNbr[k], col + colNbr[k], vis ited); } int countIslands(int M[][]) { diff --git a/Graph/prob4_graph.class b/Graph/prob4_graph.class index d873b12188266c455d1c82025f00e9a848c611ae..33b3f227390d8d78e3c56fbd4ae6b5babd6ba277 100644 GIT binary patch literal 3085 zcmaJ@TTmO<8UBuLE5tg0LBtBkmJPOLBrYLo;#v-_jV~zXVpkYybo$!%r7!JFI-O~!FP$l4n|@~{EMb_;&Yu0x zIsf_p@4xQ({e#bb3*cFN7(f)K8_9EicvX?DHxZ_ z69JyP5I{37D)_qmo|Z$Z0h72Ssi^>_@eKu+18B$TMx4Nif-3=pDwC94nUT{GKdwsN z7v$vpZbH-KbXGxH>d44J_v571_>LQ`K{MdVWmHSLceB$(+e#x#Nu{oujR`mA7(M)<|o)lvS`V5xc4KsgTys8q&z-e8HN1`dYT2<>&fj095oNq2dU71X_29h>95EDi&a> zu#i{rG72h+uvL_>sNyD;1X`Sf^%kjE#w``k;8_)~;8j{ylkK=j#cNnp@VbgO@J$up z!jghFRlJ4U0&O*3MrmHp$kZVA+VYg1wk_iLw$#3Va!xPk5q*hV#fTP3FQ;>Q#4scF zoE~v3m2$sB0jDg>F50wxOtw?!1-XOy;edv?4EAbF7ygohkbR zOPp1;W&2?@1@L|RfKd_=*8PGuuMb;hTC=AOdyZ7m)=ay&EfUq!>?4kH1wWJt_r5^4 zlLn6C40F+%*ZV816`^M}nd8d}e##~`YFYCoTBRmUQ!fnXv|>@GrjP2~S(Q=A?Geq) zR=M&dsU`mU-26V-a|fcQ<5ReL*5JN;2cA#ibwAhH z@iF%F{0iRcVi~^a+b*%X@sCd&af2N9Lg5&Ohg1Xhp^YFqaDdA9Q%yIX;%*CE8~jPS z6?6#!tn)tz*(|Ck28dRoXp^cs%1}OsyYtuZOLbBadkV(@xq!oHrG-NFOU|VY?@_h1 zD%soNnXHpgM#C{r$a5C~fuEsUQjG$iLoH+1Gv3~y_o)>$_5{80-ZCCr-S|_y!%^Af zsB}3h578p9t$XOgHo9;x`Z)Fz`T&lT;{>f6;Y`}dTf{xIDL8uARdx1P3G)~d93@Qp zln-!e4b60L%P66`e&ZQ)4}~T5F?Pkn?#bJ3diOsM*V^M@q73weV{w9XHou6Kv3mv0 zzeFpkwladN8~?6_V~|%DdH3=2D$_*uAp!{V+l3**l7PR)*$~ImIEOR5%$#%J?}6_D zS`;)ZI4;)Fat}hZt;5?&_-xJ{^}&t@7B;xk33#;#S^h`-wGa!hZ&K(*yF;qWBT9RLu&|;^@(Gi_+4}e ztRPFGvliBnC+Ky;7@n4hg5C-w3CI`nRdbw%Wfz^$_)Z%lCNd%l{(TuSy z#u=LlrqTsQ<02z5#)sESKG!e>owvk1=|x;&rC#N){{_5@7x58ye*q1Dz%2fZH2zM` zFK`|IL>B+T4g44Lc)*Lu23{8XP!MqxML%pO&Zp3H9}NnI#C?PmS&~Qphb{)%Sv?{4 zIAlO52;IjZKSu}F;o@TRJ@`0VXZ1BOdrnr<`X(z^)@5Q1U6-4EchEf=^V91GV}7?B zmC8te9gKN>a`Z`Bdh!rG$rL^;ol`0C9#)ZTN&()9nsJLQ;}vw`Rd$otsP=VM-y1Ca jH<`e1QSB-6x-iTJAgfQ{NB9YT%!GfDb3f>*qH$V$E%^;}Apba$0JR_ihf)hA^2sX$}fDqJ`VdK_?dH=)2 zA&_WdT>D$xxg&_4i{>TgR@JRKb*kQdn|zbE|KsG#H=vzOpE6o=NYG|z_X+=VI-J$% zpv%Y7?W~>{b@V#uGxWRgfUml1KKTq9hTPfeU^s{C+;G;2&nRPtn=bK|gYhU6KCw}5 zJMWI+?z`{5ynDfCZ_K+N6om$(m831_C=W8B{JtvSe8B$U9AWvA4FFp4`hUZdewXH9WU0v20mk z&ai4(W8EXRv%9^}GQYB$*;%zYRC38u%jMv8xIMatN*hQAhvD?6-{B1}*p4I`xS&bO zw9Sw{2|u+Y98WhcdXb1uF)30N)SAKJYWd|Dp-&bua98s*G)SME%H&w-s$X5$gUcgz!HMRVz;HR0HaJSVWhossRE2l(lOR1OK7D?@) zf_@1dl~C7CfBBd~LtRbizw~-BYT(m;L3DZFF>QKjFp}*s+u0u}I8%H;N$P;o532VxIogIV>=1V9Id*B6-I~2ezob{H T`!riWZ4ByWNEOY>4bk!!ADL+= diff --git a/Graph/prob4_graph.java b/Graph/prob4_graph.java index cf84b48..88cfbc9 100644 --- a/Graph/prob4_graph.java +++ b/Graph/prob4_graph.java @@ -21,8 +21,7 @@ * */ - -//dfs +// dfs public class prob4_graph { private int V; private ArrayList> adj; @@ -71,6 +70,51 @@ public void topologicalSort() { } } + // kahn's algorithm + public void topologicalSort2() { + int indegree[] = new int[V]; + + for (int i = 0; i < V; i++) { + ArrayList temp = adj.get(i); + for (int node : temp) { + indegree[node]++; + } + } + + Queue q = new LinkedList(); + for (int i = 0; i < V; i++) { + if (indegree[i] == 0) + q.add(i); + } + + int cnt = 0; + + Vector topOrder = new Vector<>(); + while (!q.isEmpty()) { + int u = q.poll(); + topOrder.add(u); + + for (int node : adj.get(u)) { + if (--indegree[node] == 0) { + q.add(node); + } + } + cnt++; + } + + // Check if there was a cycle + if (cnt != V) { + System.out.println( + "There exists a cycle in the graph"); + return; + } + + // Print topological order + for (int i : topOrder) { + System.out.print(i + " "); + } + } + public static void main(String args[]) { // Create a graph given in the above diagram prob4_graph g = new prob4_graph(6); @@ -83,6 +127,6 @@ public static void main(String args[]) { System.out.println("Following is a Topological " + "sort of the given graph"); // Function Call - g.topologicalSort(); + g.topologicalSort2(); } } diff --git a/Graph/prob6_graph.java b/Graph/prob6_graph.java index 0714e93..9a42eab 100644 --- a/Graph/prob6_graph.java +++ b/Graph/prob6_graph.java @@ -26,7 +26,7 @@ boolean isCycleUtil(int i, boolean[] visited, boolean[] recStack) { if (recStack[i]) { return true; } - + if (visited[i]) return false; diff --git a/Graph/prob7_graph.class b/Graph/prob7_graph.class index d27a59cead6dbd4397bd9817e122df25ba50a42d..593b326d9d080739410a2b738dbb82485d7b5ba7 100644 GIT binary patch delta 129 zcmbQlKZ$>X1*@PI0|$dP13!ZfgDQ~LX3(4L$$Ht>h=GN{1Sn(1z{g<8AkJXLAj@FQ zpax{?FxWE~FgOBbof&Ky+>2>X1*@P20|$d913!ZngDQ~LX3&}J$$Ht>fPsa<2qU@&605n$WH70JxvAIZY%AIZw$AIT=b<{!x}!0sQ(A;2;D c6QjDQ5`zqbDuXP8A%h$PBZB}?9}|Nh04CWBumAu6 delta 55 zcmX@avW{iLT}Dwi1{NS>V31?CVco+O$;{#($-*|7jY(aUk3oh(kU result = new ArrayList<>(); + int curr_sum = 0; + for (int i = 0; i < n; i++) { + curr_sum += arr[i]; + if (curr_sum - sum == 0) { + int start = 0; + int end = i; + result.add(start); + result.add(end); + break; + } + + if (hm.containsKey(curr_sum - sum)) { + int start = hm.get(curr_sum - sum) + 1; + int end = i; + result.add(start); + result.add(end); + break; + } + hm.put(curr_sum, i); + + } + } + + //method 2 with constant space + static ArrayList subarraySum(int[] arr, int n, int s) { + int start = 0; + int last = 0; + boolean flag = false; + int currsum = 0; + ArrayList res = new ArrayList(); + + // iterating over the array. + for (int i = 0; i < n; i++) { + // storing sum upto current element. + currsum += arr[i]; + + // checking if current sum is greater than or equal to given number. + if (currsum >= s) { + last = i; + // we start from starting index till current index and do the + // excluding part while s(given number) < currsum. + while (s < currsum && start < last) { + // subtracting the element from left i.e., arr[start] + currsum -= arr[start]; + ++start; + } + + // now if current sum becomes equal to given number, we store + // the starting and ending index for the subarray. + if (currsum == s) { + res.add(start + 1); + res.add(last + 1); + + // flag is set to true since subarray exists. + flag = true; + break; + } + } + } + // if no subarray is found, we store -1 in result else the found indexes. + if (flag == false) { + res.add(-1); + } + // returning the result. + return res; + } + + public static void main(String[] args) { + + } +} diff --git a/Heap&Hashing/prob2.java b/Heap&Hashing/prob2.java index 30114ed..f6368a5 100644 --- a/Heap&Hashing/prob2.java +++ b/Heap&Hashing/prob2.java @@ -66,10 +66,8 @@ public static int[] topKFrequent(int[] nums, int k) { int[] top = new int[k]; for (int i = k - 1; i >= 0; i--) { top[i] = heap.poll(); - } return top; - } public static void main(String[] args) { diff --git a/Heap&Hashing/prob3.java b/Heap&Hashing/prob3.java index 2cbe949..d4dac0b 100644 --- a/Heap&Hashing/prob3.java +++ b/Heap&Hashing/prob3.java @@ -3,6 +3,16 @@ import java.util.PriorityQueue; public class prob3 { + // Time Complexity: O(N log N) + // Auxiliary Space: O(1) + // public static int kthSmallest(Integer[] arr, int K) { + // // Sort the given array + // Arrays.sort(arr); + + // // Return K'th element in + // // the sorted array + // return arr[K - 1]; + // } public static int kthSmallest(int arr[], int n, int k) { if (k > n) { return -1; @@ -19,6 +29,12 @@ public static int kthSmallest(int arr[], int n, int k) { return heap1.peek(); } + + /** + * Time Complexity: O(K + (N-K) * Log K) + * Auxiliary Space: O(K) + * + */ public int kthLargest(int arr[], int n, int k) { if (k > n) { @@ -33,7 +49,7 @@ public int kthLargest(int arr[], int n, int k) { heap1.remove(); } } - + return heap1.peek(); } diff --git a/Heap&Hashing/prob4.java b/Heap&Hashing/prob4.java index c8519b2..a265560 100644 --- a/Heap&Hashing/prob4.java +++ b/Heap&Hashing/prob4.java @@ -14,6 +14,8 @@ static int maxRepeating(int arr[], int n, int k) { } } + + /* * Uncomment this code to get the original array back * for (int i = 0; i< n; i++) diff --git a/Heap&Hashing/prob5.class b/Heap&Hashing/prob5.class index 5ccf2da252852902d5e5f9e6fce5c6d321afd5a5..cf5186ca269b10b427045f0d78560a71d17d82ae 100644 GIT binary patch delta 111 zcmbQqF_mM(ViGi3(@m+f)}L9nPO3s@m*cnb^T^8b4$2Qlk&`Y{MH#4zwMBu(yOmSQsGoxF^> F7y!}E8nOTY delta 136 zcmbQrF_UA%V~E3 zKfu7Tje#>|2LqSwat2|rC`cNtm^HkGg>m`+os<2T^;H8H1Q`+-co@RV+^;n|$zbTH9DQMh zK@vsnIB9bQ9xUne%gz1n=YPi_>Hfef!;@(?k3y=72nn@l^EB&O{y8nO3hbxz#N;?{ zOm-fG^UPd1mUG8tdEGG;R?*~l?iX0a^zsX5Sd|VoXGi2X-99xerx|&2jOL8W@LAjz zK5E}nfHhmJvg}ZMRX`O`1>O{p^C4gp3_Yd}?a{%`UIB<@x~=h9?h+Cccnm$J4mm{cn7H z|IY^Ln<}6R{3``aIci3AQu4L6Ku&6Hz;?_gCi7B7nT#0V{)cs=%)*@Cxx@p11%2 literal 0 HcmV?d00001 diff --git a/Linkedlist/aindex.txt b/Linkedlist/aindex.txt new file mode 100644 index 0000000..e9d0a26 --- /dev/null +++ b/Linkedlist/aindex.txt @@ -0,0 +1,29 @@ +1. Linkedlist operations +2.Detect loop in ll +3.Find mid nod +4.remove duplicates from sorted and unsorted list +5.find length of loop +6.remove loop +7.get nth node +8.get nth node from last +9.reverse ll +10.Intersection point of 2 ll +11.Merge 2 list +12.merge sort +13.swap node withoud swaping data +14.check if list is palindrome or not +15.swap elements pairwise. +16.reverse double linked list +17.Segregate even and odd nodes in a Linked List +18.Rotate a Linked List +19.circular ll traversal and counting +20.check if list is circular linked list +21.swap first and last node of circular ll +22.delete node from circular ll +23.multiply 2 numbers +24.Rearrange list +25.delete node having greater value on right +26.Rearrange 2 +27.Flatten a multilevel linked list +28.Clone a linked list with next and random pointer in O(1) space +29.add 2 no represented by ll \ No newline at end of file diff --git a/Linkedlist/prob17.java b/Linkedlist/prob17.java index 1740d9a..6bbda54 100644 --- a/Linkedlist/prob17.java +++ b/Linkedlist/prob17.java @@ -81,7 +81,9 @@ void rearrangeEvenOdd(Node head) { even = even.next; } - odd.next = evenstart; + if (odd != null) { + odd.next = evenstart; + } } void push(int new_data) { diff --git a/Linkedlist/prob19.java b/Linkedlist/prob19.java index 25b6cf3..ed37781 100644 --- a/Linkedlist/prob19.java +++ b/Linkedlist/prob19.java @@ -1,8 +1,8 @@ /** * circular ll traversal and counting - * */ + public class prob19 { Node push(Node head, int data) { Node ptr1 = new Node(); diff --git a/Linkedlist/prob2.java b/Linkedlist/prob2.java index f1c2684..106a2d2 100644 --- a/Linkedlist/prob2.java +++ b/Linkedlist/prob2.java @@ -1,5 +1,7 @@ +// //detect loop in a linked list + import java.util.HashSet; -//detect loop + public class prob2 { Node head = null;; @@ -77,7 +79,6 @@ boolean detectLoopUsingTwoPointer() { f = 1; break; } - } if (f == 1) { return true; diff --git a/Linkedlist/prob25$Node.class b/Linkedlist/prob25$Node.class new file mode 100644 index 0000000000000000000000000000000000000000..e0b7429d7e00a6272e55f94ae6db2858de186c7c GIT binary patch literal 410 zcmX|-%TB^j5QhK5rG-+Y0&-EjELcEI#F!XOG;TjhL*D0N^I-c(a{me&7H&%5F?s_d`+k(;am!s zqacvc(0Afk#scN>a}>HKr(Ko35YUoGFYX=-6n+ybcIgFPa>d@>UvSi)k~mC>m9ZDd z$@0mS(Y@pPoMGIB%V;LAJ>`_v1CAEX3l}O(WSrcDaiU|_L>U_Y3sDp zslDxOuf5^A9SSo#(@QUU(dlJ>La+J@TIq9kSAybnCi|ZEyyyLR-j8$g+l!~a0(c*H z5@?4WM-u&UG+`h??yMq%YI`n@^B8KS=6eY$Us7ZwhRX?_Wnvgrin=0K8Zo90ud2KJOHzfHrO0vYIWKt}9(iSEN}KNaiY4XK84-M=50l8b&SK^2P+}`p(Q# zE9={)a+WRgYvm$2*~oaK7-Qt-^>Rl}@=r_DuK%1H*QDz}W5y8F7M z1|Tl!oh=7HFAp9MAQtX2p=+ zic@q`4Y<*Wk2K_9#E{o;6Ehk&W4qc}_JfrcIP3>|)ulkx z@0+qZXrsCl^Uq6cpw<_TTZV0o;S*KRPX&5vIav0(vns>h2G}OeWzVT@#BiIX%{k8M zT1DW;{jox$pjp>VyI7KLPoSAO2x*_>6~noWihP6m{*epXklA0G&_&iPl?s+8c_|kK zdJiP@CTs#-|F4G=yvOal{DL2+mb8&PhnVy&?%w9A&Z6lZh@Z#^ihu@R*i4QCPF|^& z5kWoIp7a(XIbn#r{v2)k7V7eP|1YT1je*?e?%!$h5#=f3dpgO0%1a#Y5K1>%3F#&MV#y~^m(odWiq{udVW#0*3h>4xOCDBj5Y!dm#KVW z&-{lF`M8f<5rfb#D(KHKpq4E(^z(ay_8^}D%9xVKZ|?r7BstyK-2J_lRT>FKxPmCg z$c?ka*O5(sQU*|qDjXX zn6F3(WrJBRQ#u^iQ9;WA^)Oy8;M%r4h{^kz`(cJ=tWN29d_?C2EXeE zj3W{R?4TOov@qT%JEl@U_6$u6>CPQ!M!yQpQ_gHI-6I9{^l^N(1XD67= zCn56LXGkvWpgE^EY$K&d6>0I=MxSl+X~L%|pK7E`r?q7phxBc<@;j{dZQ;H)Wn-LC zpu$qDbCN$Nj)zQigH!$mYxpJ3;42K`5qtkNC*vDV#JBuY_znghvj^WZ*FM@usF&ti ePvlL^1N0Lim&6hB^DN>m-i-_7)kVF?Z}>k=u%SHw literal 0 HcmV?d00001 diff --git a/Linkedlist/prob25.java b/Linkedlist/prob25.java index 307ff8a..12f5918 100644 --- a/Linkedlist/prob25.java +++ b/Linkedlist/prob25.java @@ -3,6 +3,18 @@ * 11-10-15-12 * 15->11->6->3->NULL * + * delete node having greater value on right + * + * revese and small + * + */ + + +/* + * 2) In the reversed list, delete nodes which + * have a node with greater value node on left + * side. Note that head node is never deleted + * because it is the leftmost node. */ public class prob25 { Node head; // head of list @@ -41,7 +53,7 @@ void delLesserNodes() { * side. Note that head node is never deleted * because it is the leftmost node. */ - _delLesserNodes(); + _delLesserNodes2(); /* * 3) Reverse the linked list again to retain @@ -66,6 +78,8 @@ void _delLesserNodes() { } } + + void printList() { Node temp = head; while (temp != null) { @@ -90,7 +104,7 @@ void push(int new_data) { } public static void main(String args[]) { - DeleteNodeOnRight llist = new DeleteNodeOnRight(); + prob25 llist = new prob25(); /* * Constructed Linked List is 12->15->10->11-> diff --git a/Linkedlist/prob27.java b/Linkedlist/prob27.java index c92333d..1a60960 100644 --- a/Linkedlist/prob27.java +++ b/Linkedlist/prob27.java @@ -10,6 +10,8 @@ * so on. * Each node is a C struct with the following definition. * + * + * https://www.geeksforgeeks.org/flatten-a-linked-list-with-next-and-child-pointers/ */ public class prob27 { static Node head; diff --git a/Linkedlist/prob29.java b/Linkedlist/prob29.java index 88a916a..9110055 100644 --- a/Linkedlist/prob29.java +++ b/Linkedlist/prob29.java @@ -7,7 +7,7 @@ * Resultant list: 1->4->0->5 */ public class prob29 { - class node { + static class node { int val; node next; @@ -16,140 +16,37 @@ public node(int val) { } } - // Function to print linked list - void printlist(node head) { - while (head != null) { - System.out.print(head.val + " "); - head = head.next; - } - } - - node head1, head2, result; - int carry; - - /* A utility function to push a value to linked list */ - void push(int val, int list) { - node newnode = new node(val); - if (list == 1) { - newnode.next = head1; - head1 = newnode; - } else if (list == 2) { - newnode.next = head2; - head2 = newnode; - } else { - newnode.next = result; - result = newnode; - } - - } + node head1; + node head2; - // Adds two linked lists of same size represented by - // head1 and head2 and returns head of the resultant - // linked list. Carry is propagated while returning - // from the recursion - void addsamesize(node n, node m) { - // Since the function assumes linked lists are of - // same size, check any of the two head pointers - if (n == null) - return; + public node addTwo(node l1, node l2) { + node dummyNode = new node(0); + node curr = dummyNode; + int carry = 0; + while (l1 != null || l2 != null || carry != 0) { + int x = l1 != null ? l1.val : 0; + int y = l2 != null ? l2.val : 0; - // Recursively add remaining nodes and get the carry - addsamesize(n.next, m.next); - - // add digits of current nodes and propagated carry - int sum = n.val + m.val + carry; - carry = sum / 10; - sum = sum % 10; - - // Push this to result list - push(sum, 3); - - } - - node cur; - - // This function is called after the smaller list is - // added to the bigger lists's sublist of same size. - // Once the right sublist is added, the carry must be - // added to the left side of larger list to get the - // final result. - void propogatecarry(node head1) { - // If diff. number of nodes are not traversed, add carry - if (head1 != cur) { - propogatecarry(head1.next); - int sum = carry + head1.val; + int sum = x + y + carry; carry = sum / 10; - sum %= 10; + curr.next = new node(sum % 10); + curr = curr.next; + if (l1 != null) { + l1 = l1.next; - // add this node to the front of the result - push(sum, 3); - } - } - - int getsize(node head) { - int count = 0; - while (head != null) { - count++; - head = head.next; - } - return count; - } + if (l2 != null) { + l2 = l2.next; + } - // The main function that adds two linked lists - // represented by head1 and head2. The sum of two - // lists is stored in a list referred by result - void addlists() { - // first list is empty - if (head1 == null) { - result = head2; - return; - } - - // first list is empty - if (head2 == null) { - result = head1; - return; - } - - int size1 = getsize(head1); - int size2 = getsize(head2); - - // Add same size lists - if (size1 == size2) { - addsamesize(head1, head2); - } else { - // First list should always be larger than second list. - // If not, swap pointers - if (size1 < size2) { - node temp = head1; - head1 = head2; - head2 = temp; - } - int diff = Math.abs(size1 - size2); - - // move diff. number of nodes in first list - node temp = head1; - while (diff-- >= 0) { - cur = temp; - temp = temp.next; } - - // get addition of same size lists - addsamesize(cur, head2); - - // get addition of remaining first list and carry - propogatecarry(head1); } - // if some carry is still there, add a new node to - // the front of the result list. e.g. 999 and 87 - if (carry > 0) - push(carry, 3); + return dummyNode.next; } // Driver program to test above functions public static void main(String args[]) { - AddTwo list = new AddTwo(); + prob29 list = new prob29(); list.head1 = null; list.head2 = null; list.result = null; diff --git a/Linkedlist/prob6$Node.class b/Linkedlist/prob6$Node.class new file mode 100644 index 0000000000000000000000000000000000000000..2915f0f357e467734d5accb4b3c9ecd59fc79fee GIT binary patch literal 355 zcmYLEyH3ME5S)wc_`!jL6P{@(C=wT>K!O596A57{G6g8Tot%&(V@I}w_$`VEiGmN{ zqY&e3C~jsSv$MB9zhB<~t}*mrVc^2VK?{dAj%*wYn9HO|1VqHJQ11;XE|*F`Mn$2j zX`a-zs+rE#RheF$x6K=Y?rm0N%^lUFXgnuP^^iZy3Kef&Q&l}DX-*sOsoYcxb)V@( zdt9uNH?DMIRW}c1-PkyhkT{j-!j^Eb!?FKu0=;%%k|)K>ClG|-?Zsj9(#0mt@?We=!G z-L#7?y6md$p0G~Rf<&q=snnm)RaaG|F1zZ2((}enFe0ivejn%Fci%nd-m!oEclT!i z*O1W>L2nQ``hp0cKZpUmtG4H&w3|BONN5<=Y3tQ6qSJCgZ7v2ds*IP^=CXz>0{)DX zlLE%9ZOh73(W+KumFTLpazs<*inDyRU-={jTE_Es-n}8vG&pphPE+2|a4K)h%vxz# zRu--0B7?Q&q${)TEjxElmYj8&a-6b2c(5^=3UFeMVy)v@k(qSd3&gu)!S|uxI^6Em}OLJH`3WPGU>ZYa2r)r=b9R{wV z%|I*KG+ZX{<=*v9Xwe4=`!qZS?TcLppbtpHL=pwdH4= z8Y~MNRacfMw6jJ-drgA8GcvCPq6*R~F@Jx~a!FXs>X^oifKS8(I!jhTPC0hga+mV% zDpyt4vRxLneQM@U zDO$GBdc?kU@Vmk%%yc}li9Tgh?wg3bcFSxX{FM+t!ncJkWs7ejq-NrOd$`Ke2bJf2 zQUQBBL?Q;xkZK>1e(ug;ke>vGZ~-Q+@CWE7SJSwN+ZaU(m#~D(ctlH%Z)XwXaB&@< zV*+1b5~moo4SERsh-lFHM8ly@Ev)$S1*|E8U1rftWd1ptQv9aldzeu)_Q;P@O0D^% z&G^%UKgrq9)6{*21-!!&&XV^WVq`FY zG+AcIY@Q50V)pmQZIPCbahL2Ahc5W{5vVcPM_+Bx^A9xI_{&h|F-IOgg|MREKd-kc{5A}-i=NoVNt1?c zgbzD@m^}n!sdA3>l~ndIl31axt0?gE6?^1sl<*B~dL;QW7GB%Xu- literal 0 HcmV?d00001 diff --git a/Linkedlist/prob6.java b/Linkedlist/prob6.java index 8aa5947..4cb9bff 100644 --- a/Linkedlist/prob6.java +++ b/Linkedlist/prob6.java @@ -1,13 +1,33 @@ + /** * remove loop * */ +import java.util.*; public class prob6 { + + static Node head; + + static class Node { + + int data; + Node next; + + Node(int d) { + data = d; + next = null; + } + } + + // Function that detects loop in the list void detectAndRemoveLoop(Node node) { - if (node == null || node.next == null) { + + // If list is empty or has only one node + // without loop + if (node == null || node.next == null) return; - } + Node slow = node, fast = node; // Move slow and fast 1 and 2 steps @@ -15,10 +35,11 @@ void detectAndRemoveLoop(Node node) { slow = slow.next; fast = fast.next.next; + // Search for loop using slow and fast pointers while (fast != null && fast.next != null) { - if (slow == fast) { + if (slow == fast) break; - } + slow = slow.next; fast = fast.next.next; } @@ -44,4 +65,48 @@ void detectAndRemoveLoop(Node node) { } } + void detectAndRemoveLoop() { + Node slow = head; + Node fast = head; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + + if (slow == fast) { + Node p1 = slow; + Node p2 = head; + + while (p1.next != p2.next) { + p1 = p1.next; + p2 = p2.next; + } + p1.next = null; + } + } + } + + // Function to print the linked list + void printList(Node node) { + while (node != null) { + System.out.print(node.data + " "); + node = node.next; + } + } + + // Driver code + public static void main(String[] args) { + prob6 list = new prob6(); + list.head = new Node(50); + list.head.next = new Node(20); + list.head.next.next = new Node(15); + list.head.next.next.next = new Node(4); + list.head.next.next.next.next = new Node(10); + + // Creating a loop for testing + head.next.next.next.next.next = head.next.next; + list.detectAndRemoveLoop(); + System.out.println("Linked List after removing loop : "); + list.printList(head); + } } diff --git a/Searching&sorting/prob12.class b/Searching&sorting/prob12.class index a10d287f7cfc6cf0fef3ba8c3a4385155e00b623..74b5d04d11b3f119eb1d9d749f9595ef18267f14 100644 GIT binary patch delta 165 zcmWNJOAf(c7)4KiO{(e<6Va-8KN^pQ7zhJFBql;9CMK3($QC3f{tbv&fJK>h55Cd8 zxhMC;c5HuLWmwu%$FhSWjYEb4S*qk{NDpKS$?J#ujeJs6gx07F8`ES#i--=T y&WtB>K1Aki-*h5>Q(TtRSj0 diff --git a/Searching&sorting/prob12.java b/Searching&sorting/prob12.java index a075187..9912f02 100644 --- a/Searching&sorting/prob12.java +++ b/Searching&sorting/prob12.java @@ -1,3 +1,7 @@ +////count inversion +//Number of swaps to sort when only adjacent swapping allowed + + import java.util.*; public class prob12 { diff --git a/Searching&sorting/prob9.java b/Searching&sorting/prob9.java index 211b5a1..44605e7 100644 --- a/Searching&sorting/prob9.java +++ b/Searching&sorting/prob9.java @@ -21,10 +21,9 @@ public int subarraySum(int[] nums, int k) { count += map.get(sum - k); map.put(sum, map.getOrDefault(sum, 0) + 1); } - return count; + return count; } - } // Utility function to insert into the multimap diff --git a/SegmentTree/prob3.class b/SegmentTree/prob3.class new file mode 100644 index 0000000000000000000000000000000000000000..61367eb9fec0da7791ea09c74d282900d2db2c0f GIT binary patch literal 1215 zcma)6OHUI~6#g#rxOALKMT!mxqG)ZU4-lSU2CuKR%Da6F$c+_zS(Ow)JjnVX(%FIX$N#BGMK>08wYg!Upr zrc-NJe$%7qxsG8oEvCBFsAcjE->%tSu7hbdpqG~|r@_!4UuttPea~ssa)}bh1jiW$ z&2*by)xPS8nza?rtxTpxxjGJ@SH~pI>Ntli!-1fQ_S8C!HLGJvhzpq3k;4o_*HZqE zb9=`e7j?|y633j5%ebN=ihc$q$jA`+%U-P9x2rzG!47rP)RzQ5U$yE@yLeBumru0y z_h%{$-S_IQ>s_}WGsNO;9xeJ@d(fVV`mfqfo#qonNj00Q=yn=@NhAvvPN}7pCYh%? zQ2u9Gxo7Nnz+CsRqU&gv1`u6}Y~jP=)TUCkH;DYXj03$cuZr zLi)6v+D30OwE>mT2Kc}mj2QAZbVH!QS9B>N2ZQMDTk^WJPIO&C!U0MNj6kPK4IIZb zMsW=%kVg!M=q3#5Cz2d8J>mU090VFv-v9=wR?*5=aCFo8oPS2BEJ>T1S(cSett>^f zVp)##70t5J!aV{Tgw+=A6L`327Cu2MzsJ6XvBlI@R+h3#REf&3aV`~A&P=O@y7dy_ zchISy@EQz5mC}YPr;{JBKg-D;<#h2>VQafPVwSDeVpJvQZ;`_o=IMt~MhbV3hJ$fD r!UUd>?HPSVqRmmryC^{AIKnZ+p^;>?pC1B;z9agLR=_YEkRSaG0l)=p literal 0 HcmV?d00001 diff --git a/SegmentTree/prob3.java b/SegmentTree/prob3.java new file mode 100644 index 0000000..466677a --- /dev/null +++ b/SegmentTree/prob3.java @@ -0,0 +1,54 @@ +import java.util.*; + +/** + * + * Implement a MyCalendar class to store your events. A new event can be added + * if adding the event will not cause a double booking. + * + * Your class will have the method, book(int start, int end). Formally, this + * represents a booking on the half open interval [start, end), the range of + * real numbers x such that start <= x < end. + * + * A double booking happens when two events have some non-empty intersection + * (ie., there is some time that is common to both events.) + * + * For each call to the method MyCalendar.book, return true if the event can be + * added to the calendar successfully without causing a double booking. + * Otherwise, return false and do not add the event to the calendar. + * + * Your class will be called like this: MyCalendar cal = new MyCalendar(); + * MyCalendar.book(start, end) + * + * Example 1: + * MyCalendar(); + * MyCalendar.book(10, 20); // returns true + * MyCalendar.book(15, 25); // returns false + * MyCalendar.book(20, 30); // returns true + * + */ +public class prob3 { + + public static boolean book(int start, int end, TreeMap calendar) { + Integer prev = calendar.floorKey(start); + Integer next = calendar.ceilingKey(start); + if ((prev == null || calendar.get(prev) <= start) && (next == null || next >= end)) { + calendar.put(start, end); + return true; + } + return false; + } + + public static void main(String arg[]) { + int arr[][] = { {}, { 10, 20 }, { 15, 25 }, { 20, 30 } }; + TreeMap calendar = new TreeMap<>(); + for (int[] temp : arr) { + if (temp.length == 0) { + System.out.println(true); + } else { + boolean result = book(temp[0], temp[1], calendar); + System.out.println(result); + } + } + + } +} diff --git a/SegmentTree/prob4$1.class b/SegmentTree/prob4$1.class new file mode 100644 index 0000000000000000000000000000000000000000..5cc8d06b0924a50d47b3ad3fda0beb9857b9d721 GIT binary patch literal 630 zcmZWm&2G~`7@UpmxOJU2h42$-pp}Y9o5)cmBo3`AK?K55TZDpo@oD3%f{SZM_L}G6 z0eay=B@T!)4}};nxzJkL?`QU#+1d5)KRP#m5b%f^Zv<& z{31uG%;ux_(+d^r!`n#BT%9EIOzNuE8{QuIhg3RAM`LrW)Om3fg~x{i-XyPzSiMbZ zSKgw?r!Ru~RGNO1#c5t9+5A-LPx;Kn6CY2pEwFN?O8qV`wGS670*xs2u?C-)F#@{> z0)Cifsu-uTELADczIhXYj)88t5^#(J8HI}Ttkgvn>kpNxXs_9i_)_QC=A%1c&wpWY z(FD6yRy}6H?Cf7dd}F~oF*Xg@Wu!~Sdh|7^HMu*mf}s_B#oE9QhITN!Vn=Lt#m$DH zubaUw(t6nB6STNvL2R~PQEz>z_iU-x+8_KvW61R#R;}^B1qT~Ow@sy5{|@dl+vwmP P?i-|o$IKpiHZ#A!&+K`g literal 0 HcmV?d00001 diff --git a/SegmentTree/prob4.class b/SegmentTree/prob4.class new file mode 100644 index 0000000000000000000000000000000000000000..29ac556bf50a38af94a1d245855c60b010ecfe45 GIT binary patch literal 1666 zcmaJ>T~ixX7=BK6lM|NZ!$7F9q)G`jBq1qCsX{^9SZp+b)}S?IdT~h3lx>pT%Fj(XXfUh9P|tukKw8+y?j|3k-ditla$2}8%s>DFo5@wjF2{?VGh|aavT>m3}AW?lbH98g+avefp;u&T+;9smN+hRe8`{| zOjFwVhHxC|Fodocrs1wJD9PEc8PvR0lMEw8!;~BC=8m+t#7=`GqqeMCrsLY}s(Y&~ z+awAlx3>$P(@@zJ)p|*^d|Qr>IF>n9C|Xk(Cc{K>yLewb5V?jh@8!y_ZJ75~JV&i; zwe6~0H@pm5%eHnFvz{Tt;D&VElJp92bc`d)z$y;EEHx>kBni=Z|7uKe=?M$L6eRqPkVWT zRz$7lhwW2$yYtjx;~1NXWH+(j?-6FSOMF*28}eHZ>g4PlLd^7;@gsYGx4JPo%HHfL za-ugW!+c=XWq18LZLfV`0D4e2C0mfgAZ?{r^x zCmgr-TJjC%{a?iq8mB|#MWazBfL1sv3^S)1dQ)u-=lrYhN(s%D>g*1v&2RM_Lgm!ybe>nX#>%HU?Xn0|`U-k^qQp1>mRQhNf+G@|#2574~N)2&iv0gMq9q1&s? U`)%Piz9MjDi4K!RivH>U0A}lonE(I) literal 0 HcmV?d00001 diff --git a/SegmentTree/prob4.java b/SegmentTree/prob4.java new file mode 100644 index 0000000..afbe4ac --- /dev/null +++ b/SegmentTree/prob4.java @@ -0,0 +1,60 @@ +import java.util.Arrays; +import java.util.Comparator; +import java.util.*; + +/** + * + * Suppose you have a random list of people standing in a queue. Each person is + * described by a pair of integers (h, k), where h is the height of the person + * and k is the number of people in front of this person who have a height + * greater than or equal to h. Write an algorithm to reconstruct the queue. + * + * Note: The number of people is less than 1,100. + * + * Input: + * * [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] + * * + * * Output: + * * [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] + * + * + */ + +public class prob4 { + public static void reconstructQueue(int[][] people) { + Arrays.sort(people, new Comparator() { + @Override + public int compare(int[] o1, int[] o2) { + if (o1[0] == o2[0]) { + return o1[1] - o2[1]; + } else { + return o2[0] - o1[0]; + } + } + }); + + for (int[] temp : people) { + System.out.println("[" + temp[0] + "," + temp[1] + "]"); + } + System.out.println("=========="); + + List resultList = new LinkedList<>(); + for (int[] cur : people) { + resultList.add(cur[1], cur); + } + + for (int[] temp : resultList) { + System.out.println("[" + temp[0] + "," + temp[1] + "]"); + } + } + + public static void main(String arg[]) { + int arr[][] = { { 7, 0 }, { 4, 4 }, { 7, 1 }, { 5, 0 }, { 6, 1 }, { 5, 2 } }; + reconstructQueue(arr); + // for (int[] temp : arr) { + // System.out.println("[" + temp[0] + "," + temp[1] + "]"); + // } + + } + +} diff --git a/SegmentTree/prob5$Node.class b/SegmentTree/prob5$Node.class new file mode 100644 index 0000000000000000000000000000000000000000..328c10a8c4a56481191cf08e9c18e126bd0dbb09 GIT binary patch literal 658 zcmZWn%TC)s6g^{`7#ruoBYglZ&qZRSvOsMYAfzf%MWi%c1hJnaqhJVjWIKqz=?}0$ z;vuo9y6#6+Ju?J>K-SzlbLQT2j<5aq-~Dd@U$N<ljHG%22%JPFG%U!Gon88MX zX?OvAc#oCFbAU4D1S&5*3M@Q9PYyUVqat9}>PJ}RpbHRiVez2=zlfzZm~G-S2pEez z?GU$_%i$eFxO4+6T)u&QMM$8;I7cdw!eO&ViV~YSU*Zo02Sx%|39n&oas5K^aofKn zVDn`6FG*qGqz`}%eZNln>TYuo(VoLWv7}D<{9 literal 0 HcmV?d00001 diff --git a/SegmentTree/prob5.class b/SegmentTree/prob5.class new file mode 100644 index 0000000000000000000000000000000000000000..e50e70cf7b76601f63706d167bbed0afc4774384 GIT binary patch literal 2197 zcmaJ@U2_vv7=BK($w{^gO}`tYAW|UxNGl)(np%}85^WPOl^O!*wmD6gB)egEQ>l9C zwKLo>>Nq;%j8iYsaoPgPaK(ie&UodWzrY{BFqQhAO-j;%@gnEE=h^r3dEY&o-=EyQ z58xy|Q?VCg951VAk^4~<3XZknFpjHu1t+95-ijkQDVI|roW?|mRN``(>>wYnt9S!v zI1*C-O%-9hrJ@&Sr9?i$cv~*#IFb^6hvQupFJPKuh9kwGq^!JP(2}Mp>_ka-9N{no zCJobYrx<+E!HcAn@RZu74O675<#}Px>hmQsQwze)6jw@wGjvCDx#ZyVHGNqhtGY&M zY}#<#IK!@tt1lF1^onQ1k>)th5Xu+@Q+KO2Sw@~`IhjjNk+o9R4U?fKnyYy(>1JUp zuA`I7a6*mlQWAVFH_)x<~&^641B8AUbmg~5-UYQZ@l9hMb z0$2zluR&muqo834219Qn`gz;1Y{Ol-P!&~*c@0GwxTK*BQ-g(!h6*k-w0kCA%}LW0 z1z~Hr4x6DRm(*|&0}OsIc}k+8nx4NV7O1Y>jexa6I~qXJ6}IkL z*eH-B0H+gtT?VHlbKZ|a!zU}%v#u8S!qI>M3 zdaaa-5JlMp)4eFIJcg4TRXLYL%Yavj$FE^7TSZZSuWEdp)fZ?yRyaN(m(!M2tX3Gl zY@Uv~QEleW>1MtpoPnBV{8{FjkR67zD;4n^_2$=odkmj-k+nqvJw$Nm{@3si->yS5zN!A9``=??#cp5?ZL3><-9tFL zf%bKDq+-4ebgrRm&Nr^qJWco`6x{Q*D5biyKqNp;zC~xu6Y5s0Xs?}J59pqYt)b@u zde_i5&byUv{vGxV`+rrlK53<;vjnAUrFHXhWp(S;@NJ^6#UpVM5t4g}v_7GN3HEV>867qe<4|^OVvs$ec1FEi z2dT|NkM6$ksEY?qjhC}JBKdh!RS;fNw65|qUBh2q%L5UG7ep)iw zfQQjz0=u@2c@6B8V4nno>CE)-2KLM~rf)Y5sr)NZ#3}k_oTmQ;BVM90DjsyAdw}Qz bIw( { + private int x; + private int height; + + public Node(int x, int height) { + this.x = x; + this.height = height; + } + + public int compareTo(Node n) { + if (this.x != n.x) { + return this.x - n.x; + } else { + return n.height - this.height; + } + } + } + + public static List getSkyline(int[][] buildings) { + List result = new LinkedList(); + if (buildings == null || buildings.length == 0) { + return result; + } + List bds = new LinkedList(); + for (int i = 0; i < buildings.length; i++) { + bds.add(new Node(buildings[i][0], buildings[i][2])); + bds.add(new Node(buildings[i][1], -buildings[i][2])); + } + Collections.sort(bds); + for (Node temp : bds) { + System.out.println("[" + temp.x + "," + temp.height + "]"); + } + PriorityQueue q = new PriorityQueue(Collections.reverseOrder()); + q.add(0); + int preHeight = 0; + for (Node w : bds) { + if (w.height > 0) { + q.add(w.height); + } else { + q.remove((Integer) (-w.height)); + } + int maxHeight = q.peek(); + if (preHeight != maxHeight) { + result.add(new int[] { w.x, maxHeight }); + } + preHeight = maxHeight; + } + return result; + } + + public static void main(String arg[]) { + int arr[][] = { { 2, 9, 10 }, { 3, 7, 15 }, { 5, 12, 12 }, { 15, 20, 10 }, { 19, 24, 8 } }; + getSkyline(arr); + } +} diff --git a/SegmentTree/prob6.class b/SegmentTree/prob6.class new file mode 100644 index 0000000000000000000000000000000000000000..c77d8f6170123a40fba0592d3559979c02661cad GIT binary patch literal 1804 zcmaJ>T~ixX7=BK6HzzC$q(HE-ptZF$2`Oo54HRg!rKQFKsV;(ns%&6Ow=7v)HjH}X zjb7^X)?PScXOtVf(9zV|%6MIWgg?M>#_`JORPjBVL>9|9yE*6mI`7A`&&k8Tf7k{v zh?0sp(i|sLgph7R7y4CjWQ2N>vduV#L9q-8+gY&;bBr`$6z3wy zsdy1Dsg&uwkS=hH2_-F-iyW62lqJ*l42F)0o5qHbsd$#1nRZQc(pVc|Xwt3avf))+ zlVRk^h|!wKHpc{v6tk(^&G>GPaq4ODhPk+++m6R^nGUQPR+*tIF&}6~_gt&I zJR&Nox>Io%&2dX)SJzyplPnqvhA)*h_LN5DCXCpoU6-7%lEko}qnQNl1Q7G<6p&bswSPT}aO5$FvOv~*AF0CW0R<`nodlmQIa00dQny$s6{EN z7K(DTv!EB1nm!=(QPRT!e}Z)G>k;8@BQ>(Cs-#Bi;c?*~Ea($`lj-f8l$B$0&mCmb zF?nEEi7VT;(fSPzw6|B$v59ypu1NiHMeeVnGaDvHEL=tGLz!*vJQUoiVRHl#l83N@ zvxLPkKEeoY;T%3g4quXO3m1GG4ny9-IuwpBj^p$);_YK}b3`8@_9wBdiI7d!Kp{Ls g^Z+gQ(M5E9YND@-ga0M$B`Q4*4VURq%5SLeABO{t(EtDd literal 0 HcmV?d00001 diff --git a/SegmentTree/prob6.java b/SegmentTree/prob6.java new file mode 100644 index 0000000..7ae828a --- /dev/null +++ b/SegmentTree/prob6.java @@ -0,0 +1,128 @@ +import java.util.TreeMap; + +/** + * + * You are implementing a program to use as your calendar. We can add a new + * event if adding the event will not cause a triple booking. + * + * A triple booking happens when three events have some non-empty intersection + * (i.e., some moment is common to all the three events.). + * + * The event can be represented as a pair of integers start and end that + * represents a booking on the half-open interval [start, end), the range of + * real numbers x such that start <= x < end. + * + * Implement the MyCalendarTwo class: + * + * MyCalendarTwo() Initializes the calendar object. + * boolean book(int start, int end) Returns true if the event can be added to + * the calendar successfully without causing a triple booking. Otherwise, return + * false and do not add the event to the calendar. + * + * Input + * ["MyCalendarTwo", "book", "book", "book", "book", "book", "book"] + * [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]] + * Output + * [null, true, true, true, false, true, true] + * + */ + +public class prob6 { + TreeMap delta; + List calender; + List overlap; + + public prob6() { + delta = new TreeMap(); + } + + // method 1: + public boolean book1(int start, int end) { + for (int[] over : overlap) { + if (start < over[1] && end > over[0]) { + return false; + } + } + + for (int[] cal : calendar) { + if (start < cal[1] && end > cal[0]) { + overlap.add(new int[] { Math.min(start, cal[0]), Math.max(end, cal[1]) }); + } + } + calender.add(new int[] { start, end }); + return true; + + } + + // method 2 : + + public boolean book(int start, int end) { + delta.put(start, delta.getOrDefault(start, 0) + 1); + delta.put(end, delta.getOrDefault(end, 0) - 1); + int active = 0; + for (int d : delta.values()) { + active += d; + if (active >= 3) { + delta.put(start, delta.getOrDefault(start, 0) - 1); + delta.put(end, delta.getOrDefault(end, 0) + 1); + if (delta.get(start) == 0) { + delta.remove(start); + } + return false; + } + } + return true; + } + + public void checkSlot() { + int arr[][] = { {}, { 10, 20 }, { 50, 60 }, { 10, 40 }, { 5, 15 }, { 5, 10 }, { 25, 55 } }; + for (int[] temp : arr) { + if (temp.length == 0) { + System.out.println("null"); + } else { + boolean result = book(temp[0], temp[1]); + System.out.println(result); + } + + } + } + + public static void main(String[] args) { + prob6 obj = new prob6(); + obj.checkSlot(); + } +} + +//ngo data collection appliation +/** + * It is full stack application + * Here react is use for frontend of web application, react native is used for mobile application, + * node.js is used for backend and mongodb is used as database + * The main goal of project was to convert traditional paper based method to full automatic system + * The basic idea behind this application to collect medical data related to various field from villages + * by keeping few constraint into consideration + * 1) we have to collect data in their native language + * 2) Store data in local storage | cloud storage depending upon network connectivity and sync data accordingly + * 3)We have to find insites (analytics) from the gathered data. + * + * React mobile application: + * 1) i18 library is used to make application in different laguages + * 2)NetInfo module - to check internet connection + * 3) react native async storage - to store data locally + * + * React web app - + * 1) chart.js for graph analytic + * 2) redux for state management + * + * 3)Backend + * express - to create backend server + * application consist of mainly 2 roles ngo representative , admin + * hence middlewares are used to provide role based authentication & authorisation of diifernt routes + * + * + * + * + * + + + diff --git a/Stack/.DS_Store b/Stack/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5c0fad35a95856b84fd84045dad3d4124ecc9225 GIT binary patch literal 6148 zcmeHKK~BR!4D^N~6}a@s3GEZ;4?+~qMd}A26j4yiMig!w_Hn#{Yrn#HZB<#)NSqL= zY{@%`*IqjlDUONARqu-_(S(S`P{!f}%O2r<)}9n<;Z2v$xT80EqChXS>3N&sKQh4Y z?v!TK(gVFx=l!i7r}O);Zl!2{G32)nb=|B&gMFM8pSPEvSHr%GU;DPpZvIrpG2NiX zKn-p3>b5gv?Ck!i>Eo+PHDw-IC3`%w{6$0p6Jx*_Fa{2W0rYH^@tL5l#(*(k4D1-- z?}LXjmWoj@eLAqD5db)XISH_D7^0wvVxh~Xq0cCUV=Vic5cayooC z&FpkSaVa~__sN}HDQK%PU<~989Lep3`~UUu{GSKeoiShx925g?RL|=QkEFe|_i)^6 sJ@gjJ!hTV37lMn_is8$x_#B!9cFz~UQZWj`0 hm = new HashMap<>(); + hm.put(root.data, hm.getOrDefault(root.data, 0) + 1); + uniqueSubTrees(root.left); + uniqueSubTrees(root.right); +boolean flag = false; + for(Map.entry(k, v) m : hm.entrySet()){ + int k = m.getKey(); + int v = m.getValue(); + if(v > 1){ + flag = true; + break; + } + } +if(!flag){ +c++; +} + + + } + +} diff --git a/String/intr2.java b/String/intr2.java new file mode 100644 index 0000000..fc45abe --- /dev/null +++ b/String/intr2.java @@ -0,0 +1,41 @@ +public class intr2 { + // 1 2 3 4 5 + + class Node { + int data; + Node next; + + Node(int data) { + this.data = data; + this.next = next; + } + } + + public static Node NthElementFromLast(Node head,int n) { + if (head == null) { + return null; + } + int count = 0; + + Node temp = head; + while (temp != null) { + count++; + temp = temp.next; + } + if (n > count) { + return null; + } + int k = 1; + temp = head; + while (k <= n - count) { + temp = temp.next; + k++; + } + return temp; + } + + +} + + + diff --git a/String/list$Node.class b/String/list$Node.class new file mode 100644 index 0000000000000000000000000000000000000000..47d0035e8beca51ceacd54b1bec5df7ec517e5ae GIT binary patch literal 351 zcmXYsy-ve06orqIv}w}Nl>eVD3=C}sIxsMRSSleRRbc>iPg)D53XT-Jh}UAMkQjIX z9tv?BG5DNo-{a4|Kfhn!0Io3#(ZN9g4~JHcd>s2Y5%5;I$pu8pQptBi%j%UBh*G6w zGpll~r55PVt5TZ_+q)6y-j=E~cMOly$$~a(@5J*`$!zml$mTgODpJCydebcBeQ7s= zMO?1)H$K?Qq&5$=Ha<=xL^zAkg&(1Z{(rE2OJHd8(<)al)5l^hm-dI2BjAoF3!HP9 z4kvWD2%y3;sDdlP4t>DtiV2&ElTV0bw1tz1E!>Yb7*qEMvIvimfQSLr#gJzXcG9J<&5C6D1EC2ui literal 0 HcmV?d00001 diff --git a/String/list.class b/String/list.class new file mode 100644 index 0000000000000000000000000000000000000000..bba2759cc8a22074abb62a52938241a0010416d5 GIT binary patch literal 1014 zcmY*WTTc@~6#k~&cIkFo6fDT4fPhezmV!Q@Kzt!FX=tlSiHY%Pp%Ywew@r6zH2wkq ziLYu@j3z!};(zhYM{nOuOK7{znVB=^e3vsn{(kueU>mnASeP}DwGhEvf??i50t*S; zz@j=XSy;wR6DuZG1&nH|E(Pq8@5|19!wmu%2*me1-wW>vM00D8ShTN;M$4WrtKH_2 z>>RpB4YnEWZtzrKDpziJLAb22c1vpm2Z2;AbdR4^+;+bu?zY>~uM1dp*^r?uvr!;D zh@dH(uICF(P;~K_HtlP+=U}FPC6Pq@+kfSRFCvfGG_`%VsJZ8$sm9#itzThc2 zWOSgs_A&@%lhbQ;S(fQJ@LI)(lpoTBbep>btGgiui;}>&rW&pgFx#rW;q&DZd{p&| zffGfVag?VlSD~`b8N@qoD4H>@lk|j|t9JV$fRg^f77C&}0Ae$65^s2wHL;E>AevCoK=*W)^xI*#aA z$)6+h9&uVTKVhWr@aH9=qhGB+{0%xOQsX8)ZPCXzJ=~$AyFBeM?rAYLB7d+%L;Po` WVoFP&W)CP@(1y*OrFRJ=G4dZ}ajp>n literal 0 HcmV?d00001 diff --git a/String/list.java b/String/list.java new file mode 100644 index 0000000..f4fc441 --- /dev/null +++ b/String/list.java @@ -0,0 +1,66 @@ +public class list { + static class Node { + int data; + Node next; + + Node(int data) { + this.data = data; + this.next = null; + } + } + + public static Node push(Node head, int data) { + if (head == null) { + head = new Node(data); + } + Node node = new Node(data); + node.next = head; + head = node; + return head; + } + + public static Node append(Node head, int data) { + if (head == null) { + head = new Node(data); + } + + Node temp = head; + while (temp.next != null) { + temp = temp.next; + } + + Node node = new Node(data); + temp.next = node; + node.next = null; + return head; + } + + public static void deleteList(Node head) { + if (head != null) { + head = null; + } + } + + + + + public static void main(String[] args) { + Node head = new Node(1); + head = append(head, 2); + head = append(head, 3); + head = append(head, 4); + head = append(head, 5); + + // head = push(head, 3); + // head = push(head, 4); + // head = push(head, 5); + Node temp = head; + while (temp != null) { + System.out.println(temp.data); + temp = temp.next; + } + } +} + + + diff --git a/String/prob_str27.java b/String/prob_str27.java new file mode 100644 index 0000000..8e9969d --- /dev/null +++ b/String/prob_str27.java @@ -0,0 +1,27 @@ +/** + * Given a binary string of 0s and 1s. The task is to find the maximum + * difference between the number of 0s and number of 1s in any sub-string of the + * given binary string. That is maximize ( number of 0s – number of 1s ) for any + * sub-string in the given binary string. + * + * + * + */ + +public class prob_str27 { + public static int findLength(String str, int n) { + int current_sum = 0; + int max_sum = 0; + for (int i = 0; i < n; i++) { + current_sum += str.charAt(i) == '0' ? 1 : -1; + + if (current_sum < 0) + current_sum = 0; + max_sum = Math.max(current_sum, max_sum); + + } + + return max_sum == 0 ? -1 : max_sum; + } + +} diff --git a/String/prob_str28.java b/String/prob_str28.java new file mode 100644 index 0000000..519cc15 --- /dev/null +++ b/String/prob_str28.java @@ -0,0 +1,51 @@ +//valid ipv + +public class prob_str28 { + public String validateIPv4(String IP) { + String nums[] = IP.split("\\.", -1); + for (String x : nums) { + // Validate integer in range (0, 255): + // 1. length of chunk is between 1 and 3 + if (x.length() == 0 || x.length > 3) { + return "Neigher"; + } + // 2. no extra leading zeros + if (x.charAt(0) == 0 && x.length != 1) { + return "Neigher"; + } + // 3. only digits are allowed + for (char ch : x.toCharArray()) { + if (!Character.isDigit((ch))) + return "Neither"; + } + + if(Integer.parseInt(x) <0 || Integer.parseInt(x)> 255) return "Neither" + + } + return "IPv4"; + + } + + public String validateIPv6(String IP) { + String[] nums = IP.split(":", -1); + String hexdigits = "0123456789abcdefABCDEF"; + for (String x : nums) { + // Validate hexadecimal in range (0, 2**16): + // 1. at least one and not more than 4 hexdigits in one chunk + if (x.length() == 0 || x.length() > 4) + return "Neither"; + // 2. only hexdigits are allowed: 0-9, a-f, A-F + for (Character ch : x.toCharArray()) { + if (hexdigits.indexOf(ch) == -1) + return "Neither"; + } + } + return "IPv6"; + } +} + +//new +https:// drive.google.com/file/d/15ck14KplQW0pAW0vUWYPx11psp4IIiCf/view + +//old +https:// drive.google.com/open?id=16J_1YYow17p6PYwKklM7X0-EDzb0fDZm \ No newline at end of file diff --git a/String/prob_str29.class b/String/prob_str29.class new file mode 100644 index 0000000000000000000000000000000000000000..b189712601a876dd9dc73c692366728f8247316a GIT binary patch literal 1597 zcmaJ=&rcgi6#fS9?%2yFCZ+#}_d@ko}(%zacd#+_~WzKs1aOcXN ztn8L#qZ5T=j$@vpSDbpI<(b9xa@KX_9>Zv#h=q+phf!TxHp57Kqkjs$?6lm9xoY_= z!wuKj{Iu!03wP#xiU!UjY~VfIFmMs01{QFWHNS{4hKqH%YvvuhBE63-Z=0;9CvC4u5h>$Ybs2^`#hgyWz#D$r z8Z|}qY1_;*jt_hVR~V*F#IWq=&aQbpEnO0;vf?@J9>*#bUv!+^R)fJP*tY5BYqHri ziP?9(8IEIgoAprI)tcFy>K^Pfe?0}AI{0+2VfKOdj#syHnO;qfL*!+xR<=Ad!|{M& z`b>TOxG{|XKaOsye}nyx0_Kk_J%?x&r8lFuI{OOjXEGQr&{OL;17y+2kxfu`fsO{r z^KIe?1ItNzq?PC!{jM5FYqN>yn0kajAkBp$cr_}t>JQjS2<-?;QgC{{KxkiM`Fo^#UE|GtntXaH6b0g^1jo>~;@gc_W5$#G$;B#EXmzcy?n8r7V z6VjJQZPURZht47B#~8;5O*&#%uK8lnmG8=f9})0N!Q(($QPOHE5LgrH<(IgZ5TuNf z5K2dc$iBi-LKVu|zRC{Ue+%UR=Tk!QYgZ22fA#GBaZ*>h)4U|5NKukGYUT~9YJpha zB-Xcx?QQaAXthL_G=~-B@dyt(HRw?OfzH@ucn~3~_uXT{ixkc8@NgtpjD$+RLI30x w29wlX<75yb)O4zefJI7NA{n2MeTjSnxJ*evR2Z@(WR5~l(mF`%Df&= (M - j)) { + if (pat.charAt(j) == txt.charAt(i)) { + j++; + i++; + } + if (j == M) { + System.out.println("Found pattern " + + "at index " + (i - j)); + j = lps[j - 1]; + } + + // mismatch after j matches + else if (i < N && pat.charAt(j) != txt.charAt(i)) { + // Do not match lps[0..lps[j-1]] characters, + // they will match anyway + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; + } + } + } + + void computeLPSArray(String pat, int M, int lps[]) { + // length of the previous longest prefix suffix + int len = 0; + int i = 1; + lps[0] = 0; // lps[0] is always 0 + + // the loop calculates lps[i] for i = 1 to M-1 + while (i < M) { + if (pat.charAt(i) == pat.charAt(len)) { + len++; + lps[i] = len; + i++; + } else // (pat[i] != pat[len]) + { + // This is tricky. Consider the example. + // AAACAAAA and i = 7. The idea is similar + // to search step. + if (len != 0) { + len = lps[len - 1]; + + // Also, note that we do not increment + // i here + } else // if (len == 0) + { + lps[i] = len; + i++; + } + } + } + } + + // Driver program to test above function + public static void main(String args[]) { + String txt = "ABABCACDABABABCB"; + String pat = "ABABC"; + new prob_str29().KMPSearch(pat, txt); + } +} diff --git a/String/prob_str4.class b/String/prob_str4.class index eb82557250998b2514aaaae9a4013a93fb98759e..d6e0641bbfb53fe5c1c5aa02a5aaa799e8140039 100644 GIT binary patch literal 1969 zcmaJ>T~ixX7=8{3Y_cq$B@{|Qt$ZXQ1;pBxLa8(rNexg9f^F5hNluf6&2CIKOu6^g zOJ{V(3#VT67QLXA&NyCs>tFD~-@w?`=Op1v(An8{&w2O#c;4rI&-wl3?ymr@prE4% zVI3WaC=pd+RL5DwI{AM>!&^EuWzdRAwR&5LOU<}|ca*rS;Ytu!F{R@grZvnc|7y7F zN;9j1+z8-Z4Rac93N+1Fj^)h?_`;D@0e{@hN`bbd<;bNYPGZU^vzfg~0M&Q^=8c$Pg*RyJgI!7S%f(lfAxWdnEc zp@EN(GO&V=4Xk2K;LIT}@w{0wGoCDI_{6|n+|zL1z^C|(c@M2>>>2nR4-9+(qD>+# z5HQVLI-Abr1%e0V9CKVwugi=l(0K?l!DOcAmPni}ot#H!_BO$7hFIok><=d*mG#dn)d5q1}R@svUy15lPhiWBQ?)V*&=Rv>$8U!AJ7P)E&|Fv?)v!^N*jF&@e>yU=P8?NN(9yY zz_l{9;o}3uqC05t|45hZsBZ_pnW%pU{%2@h?2D=W4`_^S_r-P@1lzQ4s74&%9Syz# zK02RvG!urw`?>{#Xv1s#tD`}GfnK5U!UkR^=vwA)n75Id+s~oheTu-MZ?=DwARePT zHrmgW&k)>!zV?+*JbCq3YzNIt7k_~v@Ev-&Xc71gt=IfNqpg=v+n>DpQ&oBtR~J!* z(1~v12w{lGW=TA)xWTJ(bx-ddKVaicVU<^~# z-N0lOVJmzu(MH~ci0qN8AUPeXvo}F#4UE*@*_~7n+S4@%hux+(|6iq?Vkc(!9p=7) XnezPVjPnrd$dQ$c+y}TH<2(Kjz+TRP delta 499 zcmYL_%T5$Q6o$X*TXh#DGmO_^WP}kAn)V8a7aR~JEC?H2yBLBI6T%SaxNyTWklL~G z5eB29Vc`S#I;)a0(Emfv1t&@w}zP@|T++_T*0fn|uAqPo)UmIvj2XK&+u zx!v75s3bg0d1RSoPBU+L%z`56bT+p>Y-^rap7P8!gE4oehTNNAHGIyZI}X;}=Ws36 zd;1@E%bne$^Wo%$=XmL6qiOZZy^Fp_uN4!n9XH)vJaaf8ukt5EAqvG-BpMM^f^q%> zbs~-^6q{Tm6`2<;zHi-;(NM6+`vk`%wXm0meWJxY>J$GY*=Q6#{z6>z8pSCZdeR?U zFdjC2ECiYeBMYkH)k$f|l5zRk%ThH2<_~qH<-aqoa_!&hDIxJH?N`!TCae0G|6*lI hY8BzA3jcNS18%S^Xk@C*3QN=nxh08I5~Fg*{sL;YKMw!^ diff --git a/String/prob_str4.java b/String/prob_str4.java index 8fbf0e6..cc29d09 100644 --- a/String/prob_str4.java +++ b/String/prob_str4.java @@ -1,4 +1,6 @@ + //remve adjecent duplicates from string +import java.util.*; public class prob_str4 { public static String removeDuplicates(String s) { @@ -35,11 +37,12 @@ public static String unique(String s) { for (int i = 0; i < len; i++) { // character at i'th index of s char c = s.charAt(i); - + System.out.println(str.indexOf(c)); // if c is present in str, it returns // the index of c, else it returns -1 if (str.indexOf(c) < 0) { // adding c to str if -1 is returned + str += c; } } @@ -50,6 +53,6 @@ public static String unique(String s) { // public static void main(String[] args) { - System.out.println(removeDuplicates("aabdgh")); + System.out.println(unique("aagbdbgh")); } } diff --git a/String/prob_str6.class b/String/prob_str6.class index 1f81301e7b4efcad1d62263de1172cbfcf959ddd..25773c74b9118f4a7de28f9342e4d9cec64ff5d3 100644 GIT binary patch literal 1978 zcmaJ?ZBrXn6n-w*BqS^Z1BA8`3Y1FTAhj=PO8})&Y-%9Y&>}@`H(>|1gxxgRbcU~v zKf>uJ$1i?zM*NU=u)`1VSNJ;|M}6)lkRVYqbNAeH&w0){&pG$<+h0e=0B)n`$1oy( zL=p2Lj)Whxn3LP2T(0>sg!hBAyd|ZSlx}-*$B#bgG=#fSnh!!?L3%FAWl0`<;Khet zEDLxR4AZce1YD8mV*w>&ZR-MooMGx~_5Gq=UDt|bYCN@iv7o;Yn2F?`YcI8ASu=N% z1-ojPJL&TpiPc}QwbI_IR%t=_nh?vil0a`$&SnLMBU{;M6QOP!~34o{O~tajJ(#pim-KBHYtU6ss zn$#Fp@*yX{rn|1~vmMPu&#DEy6=_r^sUuycNA|^2+SRJd1Xd#1Xoi`~wmQQleNN`1 zbLRZ`0-FLoLI{lRYkPXeGE17hVc5HrYPM$DweHiJX-!)vT6fECamj$Tz5TCBnvABS zPh>(90&b^ZFP_N0d@V5DCf_h$T6=oy<}`C&(Mq;eJ@DcgiO5;jUcJJ>&YGrP&6KrT zO=ltBbrRRYXb#PN&D<{Qwdtl~m%G?8#b+GX4=Q>W^UkS1sp~vMMk|*KhOMW)&;+iY ztFK#b0^|R0$B7=|dnf-qe6x6!xQ=oc=2!6Rj=hFBq`)_!Wdtbj$?McIHQ=HKNW>cG zd4;}T;EFe(9L8J?xEEte1D>_n_#1d<<6}qY1t?0y9tUwsY8c$h-vH$R{7j<{??S}{ z`uPM0D1$LXfXBR{t+3xv<>tX+*RW$tPT+avqQcNVt|zgj96n+c=HYAS5tAAOnZ*$E z7-rNE^BCpt0>&A1nps?9_ytmPnvYN3dKMxXnaZ}TiR2nmm} z=oo9_|2@jrF^4-y;x45{+~C7{6Ay3;1*9Ab`k?%YfEfD&ZcnR(D=c9eS6eMgvD6;I zhdginn=U24skrl-ZcjePmIOE2Q#IfaH;+N2$@v0z?>U6b;46OpMBBnse94)+&iw!} LZ%}vBS=0Xjo&K|> delta 401 zcmYL_OHKko5Qe{IfSwsfN5{8_BBBDmpWuU0Q5Gh;@do%v*cgnkHJ-uD1w4U?3!`D- z0bFid1bJhHXX|wMa5%lVUtPPK1!QNigY2 z=d{U;$*d-)$v@PugFEG)b>kb=iI`rZxdMb@ZtJ%7( z-JD*v>W#~$8>eVea@b;9Vbsnq6a>}Cm$AcckTZ@=O*v!_f=?r_4ufywMI8lC(Gx!* zGl$DSAu|ZNa!N@Q31Wp;)UzaFDj4q+6;?Qh subSeqII(int[] nums) { + ArrayList result = new ArrayList<>(); + int index = 0; + subseqIIUtil(nums, result, new int[nums.length], index); + return result; + } + + public static void subseqIIUtil(int[] nums, ArrayList result, int[] temp, int index) { + if (index == nums.length) { + result.add(temp); + for (int i = 0; i < temp.length; i++) { + if (temp[i] == 0) { + System.out.print(nums[i] + " "); + } + } + System.out.println(); + return; + } + + temp[index] = 1; + subseqIIUtil(nums, result, temp, index + 1); + temp[index] = 0; + subseqIIUtil(nums, result, temp, index + 1); + } + public static void main(String[] args) { - subSeq("abc", ""); + // subSeq("abc", ""); + int arr[] = { 1, 2, 3 }; + subSeqII(arr); } } diff --git a/String/prob_str7.class b/String/prob_str7.class index d56eb0a548728f85ec2f1e2b134ff94132fe7171..fe500ecab0445d3adb3ad72d0fe66757110d0e9a 100644 GIT binary patch delta 626 zcmY*WO-~b16g_X=%)FV`C#_Xbuv0++%Tz%MRz$1{sDONkiP4q8pot{L8tKjjF){9& z*}2iUP`6;Lrirdx8GnEq|A-;#dBuddm~-!a_q==VdGl4jOx^hQyZHscX87 z-67i06XFPtYV@Mdp7mQeW}%QJ{kVk_n!LdPLjg`I3@elb#45kp`plRp)Svb-dovma z6RQu_9yGeDV#AF$6133oHMB4yoCz_naOIkwqARD z=h4Ew+WqR?^|X(R0VWNmFm2(IK?e>9$l=mRa$Ri8%eay(JJ0`BwIt~w;{wYl*#Nw*Us8c z&=1*iqq8QvC!;90>r+z@bQp3(fJ6U13mfnx4eru+p2gw79Gebzy2_|IeijRuqv`I0Dcccl)XQD$@;HyyY7uQyCPd`uSm$KC$#`LfD6$FgUI+m2Pw8ePY_=MHzh z+%`P-*^ICi_Dp^DLB_UchusK!o++jcc6F`09^RSLw8z8nHu+F_6zTnNk}R2Lp_v}r z=Z043rLB2WO=n zq}z>{erBa?3>n)gQ-w;|uy2OA5gBaS8QYl~X)52y-zVnF-(LewOo*P#6vFfnC!#U;ACbdkzvz4jC_NOOTOL#qaVxH{0T=tyT$>(WaD#&-?W;@!)dfJ}Lb^kWexvbCG zr{gQhvyyR62jD)T4h``O#58tt)9V9r&y3C2vtjl=C*G~`t9YmG>IkKX{Ez{h*({68 z21N@4!hkUF!2tIMAA>Qlm>Sfr14>^3fF8_R@T|`&pw9+iU@a@D~2-D zVfSrZU@?v@jqHxC~UyYn{*kz1jDFcappb1H!<+ zVnBIOGYYXKd$txf$7ijNag4#jaj8K)1B)qu~2NHo+2a1#(>?7j2x4BSR7dX=oRQ&n~LPz`~%-z{;S@z{8-&Aj6=~pv+)6xrM!7(iF%tV{l_IXYgdOWC&ug RXNY2OU`SwaoUFr<2mnJ^3L^jj delta 63 zcmeAb>=oRQ&n~LLz`~%(z{;S_z{8-!Aj6=`pv<5*xrM!7(g?^hW^iLLVen)yV+dlf RVTfX|Wk_JKo2M#=?GZn7sMexJn>*5|r7n%tJgP-~g<@wKce7j3ph0^wrI~%Y_G1B>Xx3uC zPHfSERvl5y-S3S>(IXB|a@64|o_07!uS1eP z#c_udoOC!v!r?T_9nR42@Ql`;)#5pxSG?fxA}=|-tdq~u>z0`d8qU#cU{%GNnjK!D z&mf~T9#8Znx?^3@=0t0}sVCiw>*Kt`tGwp$I!6_6IK0UPhqttNn|E~VUESIW18-M% zd|zS2p@8??E9OeiN><(Y(JVAQ7kS@Jw>RcbZ;u^{6&#FpwiHBTiBTit_lnzK=Ni}Ce*3ENp}X8$ zS)3!p0YiQ=RFRhGGGmd2VudkNu|RkTBW!$%IgmmZxdYyyl4dpT#&=%FNES(;ikTvp z;gez+QYK3Z1u0?)_et@!!i05{@&MJWr-hAli*=SwGMded2s=JwD?d}g?^H5IRI*?J zzCQ^nB8uYdaaJo-XpE3Kj-yyTCO4Se&#L5P$HqnBu983G&HD;#U=&aN5LR>)TTXA4 zCt`Ub_Oek_eK^lEgl`1DN!_v$rWst|V^O9Xe1Tfy&7bYPN%}AuBg`-*HusK02QqIm zHx--dp-wxJ;>r4wg2~!bkgQY~zq zrna>hWlzYyy^0*goXNErLa%Yw%VHv9M9hWwStD$iq}b=ukSUFw93@9~w4^d`lsWa* z5KDz^c{ee&X{XGre@t)63~E!Rt^q3hKQ0-n_WH!>-u7iDrB+bpkr^7q$fk%&?8z7 ac`3b^U0y$zxylF3X0IbopFkVs7yBEs`V|5I delta 938 zcmZ9KNlz3}6otR4Zu)gsKb0UYh{Uv_2#phqS8~qWAGzAp8&#YPArg${!ezdaEBka?3)1%n0Ilw{pyOmde zNOPDYni##Bqr^3RBoxOq$LZIcpht6(Ld_{oYtESHtbubR73Vb<7|>ia#g~Y?J$AVI zGI0xUL#!*RxkADsy(Sh*^d;iEd+Vc#o>*7kBp+A(T+>|VhUO+mEPTE3*q-7tO@v$S z7rWFmp9L?cd5Ue%ZSJ_6(yAwT3)UBkKX*;l12@N4XgzdmeNU}N?pI%3V_1G0Sn|l) zf*y&*1;M$(BG{>KPGlG>V!gtCo>I>foG4nDf|o1;WQ$UcHgzv=C~YN;q=CtTv+>n&usDd#H>>p@F>6mB&(s^-me1rEgpDkq q = new LinkedList(); Map topViewMap = new TreeMap(); @@ -69,6 +76,46 @@ private void TopView(Node root) { } } + /** + * Time complexity: O(n*log(n)), where n is the number of nodes in the given + * + * * tree. + * Auxiliary Space : O(n), As we store nodes in the map and queue. + * + */ + private void topView(Node root) { + if (root == null) { + return; + } + + Queue q = new LinkedList<>(); + Map mp = new HashMap<>(); + int min = 0; + int max = 0; + + q.add(new QueueObj(root, 0)); + while (!q.isEmpty()) { + QueueObj temp = q.poll(); + if (!mp.containsKey(temp.hd)) { + mp.put(temp.hd, temp.node.data); + } + if (temp.node.left != null) { + q.add(new QueueObj(temp.node.left, temp.hd - 1)); + min = Math.min(min, temp.hd - 1); + } + + if (temp.node.right != null) { + q.add(new QueueObj(temp.node.right, temp.hd + 1)); + max = Math.max(max, temp.hd + 1); + } + } + + for (; min <= max; min++) { + System.out.print(mp.get(min) + " "); + } + System.out.println(); + } + public static void main(String[] args) { /* * Create following Binary Tree @@ -91,7 +138,7 @@ public static void main(String[] args) { tree.root.left.right.right.right = new Node(6); System.out.println( "Following are nodes in top view of Binary Tree"); - tree.TopView(tree.root); + tree.topView(tree.root); } } diff --git a/Tree/Bt/prob17.class b/Tree/Bt/prob17.class index 7e17623494974c3f4c5b406be4c45497e7a30adb..4314e5b2dde259894fa686237236814639509611 100644 GIT binary patch literal 2981 zcmai0*>h7>82_Cty=iixp_F1NLXd)8sUn+QP^lo1wt&Uf7Ps5xw7E37HzYTOy6>pq zzM+Ea18>ggu+@%^5$B3OaD!x+SnhI_)OL$`7_9L5L^tL0v0d|x$FGL+V+TE@ck zn$RG_%x*k{3B^pRgQ?+&K%n1FNC7==Su)#`GIBYYBR6Z?j=+-MOx7N~aeISO>J+Hx zGA+~DDd2Bx8l+Z_Yg^T8TCzW%9+lZc#%PM(qKyj-m2P;{b{soBXv$;sJKz{&lYK_U z)z>hoA*CTL5GiSGrvJ2IS^~9=hkK70Q$~BruqN6EoUCb0bhOZb(D9^RQsW4=Ws&D^T=y>LC1?Yxgh1eMlMM+9jBDSOFCZ0D>`0P%WHU@xbI@wa!%IB z^hqaaCvsI4cq4>2b-abQb-aVq$|tdC!@I1ehnPCuD6nCdTcFq!D-^TGV@^`WCd?^m z#YRob$WF%`;?<$->0~=LF`9c9wR9)i49ho&8J1gKz zCIm#BePtv_t!ON(x97UEX+%IXbGy?Shk&vFc&^CGv^_P!S_Yk~6Ef%Fsa>F6gpD>@(#ZA8X%taSRu&ih2byb}A*XwA2lKhLdFAv>M)EV?5rZ zDw{Trb7eSzjf-Hq2!dg}hxgeWA||jhZA{7@+Zr>RA=62c$~lJR@TvMgXNC8InYcIk z*FDN!lK}f+P{SEDEFTIqlOza9Ii^enS3P) zEA{4<3-Fa}mhztzxRy3+P>Hp)*jx-F49Y4f{ki!(eBUGRxxZ@`{^3gq^vxp3y`o=9 z>MuZRQ^X8HJ`AN~7*_xeCW zxpHaGmm;GDakM`0U{M_P#OLPTYMsF{ff-Z_s4z2FF7PhaDyl{WU(pf#0=0F)8LSkz zh-=Qx{i-hSa{(JcE$Qo^5$_N-62R+GP2^XhiQHyF*vgNCHrz%??jV#Sv>GL>X@WG( z?}8^OJ;j&$G;YTG=)~9P!jI_2PuPi@=s5;0^fwxWhAkSlUco*Mk-xCUcLlnJZGT|{ z;pRKpgU>L`Xov9??!&jZAHQ(_4F>+eSfL;lp*a>g$chV= zWh*NKT)~K2m`%PIXJ7{-d2{n8r$SA~*;zz}qcxXsU2ls^hDcsOm3OFh578Flr-VgW z;aD**jVh^Duq1k}r@DD@Rgo2*SD9xm^|WTOez@fl8u|!f^@fYs*m@DymqvLTmN40I zcJTyOB8di=yz~*mI!U-vgdxpOEDI-K^MfYCu04t~{PGH*gLXdlZx{CfFCSs=gHzxq fwVtyO;#ct&+*MJDv-k)fuweI79-`(0{5|*&6t=z! delta 830 zcmYL{%Tg0j5Qe`Qg)^Bsk`yH%DEDy7fQTrlcmufyP()Egi9rxS1Vlv3O_pr6vT>p1 z$_GHXR7sT!m--TJdZLw6a`++$R8 zp9h*TViw-Q;{13+b9i8WVp8!?6K7oW$S5b6)I6qKGiBfj(~23*Q)V^KOo2IK$p*Wm za$d8*bIl?##S6_6FEwG7EizNp4XaN6vLntCuQWAOeEn;?cA~ncX4oR9x^E`F9Iu~^ z&rQ`2EiF#ZO|{evQz|VL%NtwrNe6<5#g>KyD}|NH-^4N^n^>!2SX2qR*n;^YE)b8L zD`?~q@tcTiP1tb0@$NRsKn|)$~!rBdr{y$w4N94Ax z@`P>V$sUGjr;!d}oeXx;CA-lr!|h>(UfvSry{z5``lZQJl4#SwY5AKmc`_cz7M~|` ND8Z5a_36$G`~wQtf+PR{ diff --git a/Tree/Bt/prob17.java b/Tree/Bt/prob17.java index 74a0761..0a646bf 100644 --- a/Tree/Bt/prob17.java +++ b/Tree/Bt/prob17.java @@ -61,6 +61,43 @@ public void bottomView() { } } + public void bottomView2() { + if (root == null) { + return; + } + root.hd = 0; + int min = 0; + int max = 0; + + Queue q = new LinkedList<>(); + Map mp = new HashMap<>(); + + q.add(root); + + while (!q.isEmpty()) { + Node temp = q.poll(); + mp.put(temp.hd, temp.data); + if (temp.left != null) { + temp.left.hd = temp.hd - 1; + q.add(temp.left); + min = Math.min(min, temp.hd - 1); + } + + if (temp.right != null) { + temp.right.hd = temp.hd + 1; + q.add(temp.right); + max = Math.max(max, temp.hd + 1); + } + } + + for (; min <= max; min++) { + System.out.print(mp.get(min) + " "); + } + + System.out.println(); + + } + public static void main(String[] args) { Node root = new Node(20); root.left = new Node(8); @@ -73,7 +110,7 @@ public static void main(String[] args) { root.left.right.right = new Node(14); prob17 tree = new prob17(root); System.out.println("Bottom view of the given binary tree:"); - tree.bottomView(); + tree.bottomView2(); } } diff --git a/Tree/Bt/prob19.java b/Tree/Bt/prob19.java index 1fdf4b3..d513667 100644 --- a/Tree/Bt/prob19.java +++ b/Tree/Bt/prob19.java @@ -13,65 +13,87 @@ static class Node { Node root; - void printLeaves(Node node) { - if (node == null) { - return; - } - printLeaves(node.left); + private boolean isLeaf(Node node) { if (node.left == null && node.right == null) { - System.out.print(node.data + " "); + return true; } - printLeaves(node.right); + return false; } - void printBoundaryLeft(Node node) { - if (node == null) { - return; + private void addLeftBound(Node root, + ArrayList ans) { + root = root.left; + while (root != null) { + if (!isLeaf(root)) { + ans.add(root.data); + } + if (root.left != null) { + root = root.left; + } else { + root = root.right; + } + } + } + + private void addRightBound(Node root, + ArrayList ans) { + root = root.right; + Stack st = new Stack<>(); + while (root != null) { + if (!isLeaf(root)) { + ans.add(root.data); + } + if (root.right != null) { + root = root.right; + } else { + root = root.left; + } } - if (node.left != null) { - System.out.print(node.data + " "); - printBoundaryLeft(node.left); - } else if (node.right != null) { - System.out.print(node.data + " "); - printBoundaryLeft(node.right); + while (!st.isEmpty()) { + ans.add(stk.peek()); + stk.pop(); } } - void printBoundaryRight(Node node) { - if (node == null) + // its kind of inorder + private void addLeaves(Node root, + ArrayList ans) { + if (root == null) { return; - if (node.right != null) { - // to ensure bottom up order, first call for right - // subtree, then print this node - printBoundaryRight(node.right); - System.out.print(node.data); - } else if (node.left != null) { - printBoundaryRight(node.left); - System.out.print(node.data + " "); } - // do nothing if it is a leaf node, this way we avoid - // duplicates in output - } - void printBoundary(Node node) { - if (node == null) + if (isLeaf(root)) { + ans.add(root.data); // just store leaf nodes return; + } - System.out.print(node.data + " "); + addLeaves(root.left, ans); + addLeaves(root.right, ans); + } + + ArrayList boundary(Node root) { + ArrayList ans = new ArrayList<>(); + if (root == null) { + return ans; + } - printBoundaryLeft(node.left); - // Print all leaf nodes - printLeaves(node.left); - printLeaves(node.right); + if (!isLeaf(root)) { + ans.add(root.data); // if leaf then its done by + // addLeaves + } - // Print the right boundary in bottom-up manner - printBoundaryRight(node.right); + addLeftBound(root, ans); + addLeaves(root, ans); + addRightBound(root, ans); + return ans; } // Driver program to test above functions - public static void main(String args[]) { - prob19 tree = new prob19(); + public static void main(String[] args) { + // Let us construct the tree given in the above + // diagram + BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(8); tree.root.left.left = new Node(4); @@ -80,6 +102,12 @@ public static void main(String args[]) { tree.root.left.right.right = new Node(14); tree.root.right = new Node(22); tree.root.right.right = new Node(25); - tree.printBoundary(tree.root); + + ArrayList ans = tree.boundary(tree.root); + + for (int i = 0; i < ans.size(); i++) { + System.out.print(ans.get(i) + " "); + } + System.out.println(); } } diff --git a/Tree/Bt/prob2.java b/Tree/Bt/prob2.java index 91f1936..60cd33e 100644 --- a/Tree/Bt/prob2.java +++ b/Tree/Bt/prob2.java @@ -10,7 +10,6 @@ class Node { left = right = null; } } - Node root; /* Given a binary tree, print its nodes in reverse level order */ @@ -47,6 +46,14 @@ void reverseLevelOrder(Node node) { } } + /** + * + * Time Complexity: O(n) + * + * Auxiliary Space: O(n) + * + */ + // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); diff --git a/Tree/Bt/prob23.class b/Tree/Bt/prob23.class new file mode 100644 index 0000000000000000000000000000000000000000..0d2753c98676d6ddcc712c225d2c32574a7036bf GIT binary patch literal 1963 zcmaJ?T~pgu5Ir)sWDD`-1PHXDG$n~K1_wxJiYX~^LvgW5iV4(7zhql60wKA!oDOe& z&tv=0yl1Ab^ebeNnZ9|iDU6%K zHyy_N5w343SXS_X1Ua{~zItn2f|TZB!L&_xQ9?&-d{aU&?UW4(Jz3K>)*5?7qqd4cd|`dVM=@xT*1`&C=~kGVj(*yONU7m3Q^h zZceXyUB!KG>;&1ow2)mM{>z-wrI&4=(3 z%^B{tQ?B>OxD&=l8rG3lu%Y2DHWh4X_!tEZ_i$gsCj#PAWF_>qvC6s#zQxU-X}E|> z5<;T|qt2T@M}fPeYYz1x46~rkP#J^=;}zm|amOgRCrr)S@Tg@x;EvoZC>7(&hHlj* z^v7B#Y67Ij@A2ZAS=r`^U|Dx{_E1K}7oZZ9#0P_W`mT|7?2_(oneH~Vx~tnR0asfA z{np5|+~J$rEvHtpCA<87-8J^u!A^s5^)~@bCwYh6=MvS>_t=AHJUULAB`8(lWU(hs z!UVhCdBW zYL@kq>(urY5LeDR&TgYBLCe^-QA=BTy>1ZxyH>t@jAlEn=yusM>SN7={uH)OTnmRM z4sPsMkA}9@y>%FlD%}o|)-5Y|so=*-NLh(aLKX{HKl(J{k5E1i-fam%Lf;{*q7STi5 ziw^WbL6qV2Qw}hXL1r+FOUxumZJORU80s>E-DJ)Myv4~KqXwP`zC=X9g_nqW@+{?L zI*3cg2+4W($%xYupuPJAx(kPVOUFejA{-J;sd~HP%p%Tnml5;N{Yhpzxc}`7^cI4L z=*vzBEkx}XG9+}_)8z>=CYFl7yYj1p!dd25SXvx>%MrpeM01H~z~jH0)JD%d z#o6!CDb#+dqNYtU=g>ucijgNt$`z6`O*up2X8BsZ%Gb;_)G&vy_%HZ1uHzBr@eNWQ zi5dcb;gNz~a;Gr=@#6*>@j8Va(>wMP2L9baUF0S1MKA$_PnF&!R8VF!&T<{*`YM0d F{sG!YzkUD! literal 0 HcmV?d00001 diff --git a/Tree/Bt/prob23.java b/Tree/Bt/prob23.java index a32da4d..4276b15 100644 --- a/Tree/Bt/prob23.java +++ b/Tree/Bt/prob23.java @@ -1,7 +1,5 @@ import java.util.HashSet; -import prob53.Node; - /** * Check if a Binary Tree contains duplicate subtrees of size 2 or more * Given a Binary Tree, check whether the Binary tree contains a duplicate @@ -30,6 +28,7 @@ public static String dupSubUtil(Node root, HashSet subtrees) { return s; s = s + root.data + lStr + rStr; + if (s.length() > 3 && subtrees.contains(s)) return ""; @@ -40,6 +39,7 @@ public static String dupSubUtil(Node root, HashSet subtrees) { public static String dupSub(Node root) { HashSet subtrees = new HashSet<>(); + return dupSubUtil(root, subtrees); } diff --git a/Tree/Bt/prob24.class b/Tree/Bt/prob24.class index 4b4b28409decd6e388189a9959635988eb5cc026..a2ef968573630e84375e54c42ef93d9efeb09ecb 100644 GIT binary patch delta 785 zcmYLH+fGwK6kXGvo}1J5&}tP>0YPo4Qa~==ky4dP3yMgscstmWwxqO8d-SzWet?-D z@I{{`Vjz;3=%fEYV&X^mq;XGa!pqFsd#$x+@16N${r0zh{`>k3z%*_41v+1hq6rF}hde_9hcT9wph_2Ne<*Hk$iiFbRSEA|Is)i@B$7kY~5@Rof>HElD ziY;GeFih*08_;EAbazwaK@Swdv>iH6iGDRQaGLTeMF1x)tw}Nzy(P7W?v%)>$w2%Q zK@X((91QVS?Q4x7i3A2H;|0^mOLKO-qa>9Ttv&ejI|zJ6aCjHK+!p0nyGVdcz$8pe zAxOW)z!1)M+#je%`Er?M_F(0e9du>l68Q*yfzrn6ayu~M+fXE@b+~O9GSm;lj=)k6 zQ&M3aIE?r%LY=;ZS07wh!7K_iT8aLRLc_|j&m&5=+?<67p%CRP`jN+I>NPyaQ`+tb O@cAV@#7OE`puWH;_^Q1mbO z18T3F@xt3$D=>7%@k(d>JKj2u&)Ho}QZnA`zUTcq&-@&Zy=D5(Tql8D7m{(CAT*u|QQetkO`yb4;t0YtYPEo-9cxH_k+{G1D@=ae=n< z;1Y36`8c}rrX}ZVl~w618mnb)qM4TMtVu`Ud^%rs?A76seuX(V*pN8fN}#jg8O1F^ z^`kX>%+jia;Z2mww`*0F*8NfzwRgoZErC<%`$tnMY{`OMbBc1>RCqc93>OtST+K_@ zo0AH!tK$t^5a1Dsw2lH6bqwGw?l@`Np6fYAbxwL4_L|!j!zXbp=~%|6I#zH`$9+7| z@eqq~e5TZ&>o|wkbvy$1IPRZ=PiaV?j#U&jtm%+gkE5hQ9%$ImVPaFq7Rov*uyoj{ z9>zDG<9}87Oe)-8=*S?;Qwgdg==!D$tDCauHK_u=$y`~k)6&^=FiAKd(Gej8dMn13 zoU*N=;Vqlq1|`=sERW{v>7!&H)wDe1=$he?7cnak_v}L~J?Yt&-tCTA+91e?7!(+2 zv1`kywvuE_lY78JQ{ROu;$Vv{8RZ%qg#Aol4g3{$Tu<^swb?bM>FNt0n z72b!4=;NL9S#P!pwEG>*&{p8tpB+Wp^4P-e9l7(8*CFP6yhz&$-@>|T^d_dlrXq&6 zszTUwGGT&-lQ~RzRK5IO?MF-^W#i`Y2_N5q|rrd5wQg6trjdAbz4i2>ix;rOsdu z7|P1^FNQ|=f0FqFu~g(~sx6<*JV$gN?FS5iztZ**udfny+X0evd4`VcF7)4VA(VbY z=Pr&#zenmBx|mHnKsT_9{FtP`1r5#ZBoTW zS-i&5lPvr+%N}6iBdjJzX^E9d4ka5|e2aJR7(+-issmB&Z#>j6IM6`?IJH6oE-|^{ zs`~|cR`zh}XLMv(;BuX|V`!uO3b(t8F21`7yv@V`eLsZsl|=ppdRL-*IGxWbsh!d< zi28EOmlIjis!UpFdX7Y+Czq`q0{=vIA7|>IGKzVO5`2!ejq!oLK^Dd_jGLIiExscY zoc5Dg=NlizMfyg_#3lY!tMrmZKt27vY^hgCNDW_M8)sM|aFPXIqt|u+d&B>}|1XVu B2v`6B diff --git a/Tree/Bt/prob25.java b/Tree/Bt/prob25.java index ae24152..1206c98 100644 --- a/Tree/Bt/prob25.java +++ b/Tree/Bt/prob25.java @@ -144,3 +144,37 @@ public static void main(String args[]) { inorder(t); } } + +/** + * Serialization allows us to transfer an item across a network by converting it + * to a byte stream. It also helps to maintain the object’s condition. + * + * Deserialization takes less time to construct an object than creating an + * object from a class. This holds in general and is not specific to our + * implementation. + * + * By serializing the object into byte streams and then deserializing it, it is + * simple to clone. + * + * Serialization aids in the implementation of software persistence. It + * facilitates the direct storage of objects in databases as byte streams. This + * is advantageous because the information is immediately accessible any time it + * is required. + * + * It’s simple to use and can be tailored to your preferences. + * + * The serialized stream can be encrypted, authenticated, and compressed to meet + * the security requirements of Java. + * + * Serialized classes can provide consistent versioning and are adaptable enough + * to allow your application’s object model to evolve over time. + * + * Using third-party vendor libraries within C++, serialization may also be used + * to exchange objects between Java and C++ libraries. + * + * RMI, JavaBeans, and EJB are just a few of the essential technologies that + * rely on serialization. Java uses a different algorithm for serialization and + * deserialization from what we presented in this article + * + * + */ \ No newline at end of file diff --git a/Tree/Bt/prob26.class b/Tree/Bt/prob26.class index a7d69ccf64a85622bccf58cf4d9a492d37eab7bd..faf030fcc60579fff6f20efe397e1b4610e2f11a 100644 GIT binary patch delta 89 zcmbOrI6-j3Nj6qPhGYh#$>-SIIZYY37|a;>8O$fkv0pN^X5eJ7VGw1oWl&+TV=!j0 sXK-b3UVVDdQUCQ9ju$;kzVGV=lWL1uA03+@ZZ2$lO delta 89 zcmbOrI6-j3Nj6pkhGYiA$>-SIIZYV27)%-X8O$cjv0pN^V&G)3W)NktVNhYPWiV#2 tV{m1#X9#3)U`SwaWGG^AVrXG-W|++2!myOVjbS;1JHr|VkIAYW*#IEb5n2EM diff --git a/Tree/Bt/prob28$Node.class b/Tree/Bt/prob28$Node.class new file mode 100644 index 0000000000000000000000000000000000000000..d83829c5ad5ad2870e0cf95b7a31c5a6403a4787 GIT binary patch literal 441 zcmX|-O;5r=5Qg8S&_dbLieI28XgEMk#CXxfj|+*Bgy2EL!CMO}l+@O=#sB4@G4bFJ z@JAVEi<)NNcc-)S%w)d4KRyAR;jjc1bsZXZibR{iSKA@a>=>=YLO^nXp z&p~%gp-;;6vj&|&-+Wz#WOvbN_t!K`=ZF2qF6xuP;Co$eSdT7gCz%F`hdDI_Ozf&!K$ zdr?fQp@vn`b&9U2LLsl)M=6;7j-1^{q1ZNiOp#Afc*{yQNUIs#Ab5p76E(sq*rZGj RTiDLL22QRMT%~*&_yJijNJ;T~ixX7=BJjvJf`qOK1x%r8X`3P-4*nZLn2>*wm0#gCOILOLBy5HoI|m!weVx z39lS4^`h6U0!};QrJeClcz)K^P~KbKdiw=Y5~|YtJ9Ap8p155!(rjVs-#Y zq!SoKW`IjpEjguoYXEO!PD%Mu!rx8cJ>1f;prErF786*)?F6syD3gLxFKc*TAX;(i zQa~@+wseb@;d#=d)^!|TAX#p?&d&T&N`VSg?@6Q1t>wynf%vj%oBmyazI0}j+G5~o zsBGG@(r)fZcf;7R=zD6#v<>%Q!DOvT6T4UX4bsP+| zT+{YLc(iGlw!lRC%kpDm-^g2ry_>K41nd@+ZU1u3>V%c3I&HTm*Gv_}V3^6AGUBNs zJ%3%QAUz!yF{$G&CUjiJw2li(Ic^Unk8xi^Nyh_x!qS9n|I!8p)KJ#3j*23DsAF6)%wU>MyO})Pc`R$JO4O2HbBnp= z?w%@A7g0U%eA#5toi;DV!z!3g{*kH?3n7iB>QvqEnWrcv@Ccs@M8u51`KHm3MaQlg z{+8+QQSyAl_Sx_8bSZPXo&sY5?@8~BD(Hu@I&GtRFcMg`ebdT^`H`XzJ-|3$0%&$eZ#I>(o2QN!s)bnG$#x<4qEaIc<*qYkz2<_(Xgzl>C1wKF9fci zO6aWE1g8HVhpYUy)f>>qKWB_9)HHMLSEJ262BBu2>l9CyxeKMu9z#5(AaIFmJWy%@ zV4AXmev1fyz(VdNqEEBAUl2J$-!nvCVlbOKMC=Jhay%X)!j+16?q@_5E>4{C9SMAA zk)S+}Ilh2@$ zqyISufFmRnU-`-Fzq*8@qyk+=F-M|2iEajtqx3RKtE;39Q~Z-;D#f2(U~u~wdO7z3 z$?e?suQ<0goH)kNA%^LHxJRo8+Q@&jLxDD~v@BB({9+e=@?yHzBHm+>>R2dWtYeOQ z>UWN5sV1pN#+7gqy&5z^`zCr;9SjKmJ$$r2Je#9y<*G{yaxgsXmrmnlN^%q#J m6fYyV&USz&zRY-o(kOLFPT3gcDmJmfX?llpKM^Cg@<~PviLUA3E&Dm`#t{n#{MR1I7iBZxprI&2I zV(rjUJ!#$uNf3rvpJLvA&zfR+ zJw!??mvhwaqzux}#B2CYtBv8}f7{_QJ+&&mr+@%bC5CA{N2?Hh8GXg*KGZ7qWRl%I3vDHZO_UOsroz zKyWF3h;D}EsY56XKVXq2Jq*v$J1dL`-r1};LRh`iQ9kpI`(~wI&_5zQ#TnoU2KJ8r zr1cY=-8XVn4 g_=`gLi2_d2BntEm61oQ{K_k*`(mFuvTl7EsFPp>dO#lD@ literal 0 HcmV?d00001 diff --git a/backtracking/bt_prob3.java b/backtracking/bt_prob3.java index c3dd6f6..a9a8f92 100644 --- a/backtracking/bt_prob3.java +++ b/backtracking/bt_prob3.java @@ -1,3 +1,60 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +//combinational sum +/** + * Given an array of distinct integers candidates and a target integer target, + * return a list of all unique combinations of candidates where the chosen + * numbers sum to target. You may return the combinations in any order. + * + * The same number may be chosen from candidates an unlimited number of times. + * Two combinations are unique if the frequency of at least one of the chosen + * numbers is different. + * + * + * + * Time Complexity + * O(N^(M/T + 1)) where N is the number of candidates, M is the smallest + * candidate among all the given integers, and T is the target value. Thus the + * time complexity is exponential and this is expected because the algorithm is + * recursive backtracking. + * + * Space Complexity + * O(T/M), where T is the target value and M is the minimal element among all + * other candidates. + * + * + */ public class bt_prob3 { - + public static List> combinationSum(int[] nums, int target) { + List> list = new ArrayList<>(); + // Arrays.sort(nums); + backtrack(list, new ArrayList<>(), nums, target, 0); + return list; + } + + private static void backtrack(List> list, List tempList, int[] nums, int remain, int start) { + if (remain < 0) + return; + else if (remain == 0) + list.add(new ArrayList<>(tempList)); + else { + for (int i = start; i < nums.length; i++) { + tempList.add(nums[i]); + backtrack(list, tempList, nums, remain - nums[i], i + 1); // not i + 1 because we can reuse same elements + tempList.remove(tempList.size() - 1); + } + } + } + + public static void main(String[] args) { + int[] nums = { 1, 3, 5, 2 }; + List> output = combinationSum(nums, 6); + for (List x : output) { + for (Integer y : x) + System.out.print(y + " "); + System.out.println(); + } + } } diff --git a/backtracking/bt_prob4.class b/backtracking/bt_prob4.class new file mode 100644 index 0000000000000000000000000000000000000000..e366cbbb3741b8c75d07aca1334143c978ca43fd GIT binary patch literal 1578 zcma)6TXWk~5dMy>TNJrfov7f%ZqhcTz7cZ?3B@73xD*UdRq6s`G7QMJ2r9A^WH~eG zGrxi-U^>%R%0n)|^au2vKf^G<9?5QEPaYVLkIt^n?tc62r}O-u-<|@x>1@-{K|q1)r=3}!h#A_h%k#a2xMwxP$jKe1N)!mywb2p@xsp(6EWS46IE5MH!}sd-zz!eGN@KU{FQ?81$%Y z1lMdov^(L*6%92)(kE^7{ea$xG*I46<|L;z-*qXD#1VCR=C}{u0;$XDcDY_o5EECb z7CvVoSBBzciE+D#6_|Y2>k)&t#cO+T|NNyGnA(V&4e3C4&{L70BX(|LNs!&<3 z(m5(QN1g=cp>pXCv;Ik0CGtPY{(zYx&sI8sbObqp&z|O1MMKO8&wj=ihM0Q{BO@5% zGGB!5@{f?7;CkfAKIZ#trN}sh5{DN{*~rnQ<6mV2!dEICVTy#(J%UR4zZcn)e}Cd# zC!(%bk)nNukk1k7c|x7T0xn>M)-@~=0~b-lCEUklbg_g!z2Bp&_X0(wAkF@b1Y4M{ z{6#Irtu7FOixd=d-KNBxzztpgLv1B>)oclZ*%C#wCF!!+l6A>!Ddf>5#cY&x> combinationalSumII(int[] candidates, int target) { + List> ans = new ArrayList<>(); + Arrays.sort(candidates); + backtrack(ans, new ArrayList<>(), target, 0, candidates); + return ans; + } + + private static void backtrack(List> ans, List templist, int target, int start, int[] arr) { + if (target == 0) { + ans.add(new ArrayList<>(templist)); + return; + } + for (int i = start; i < arr.length; i++) { + if (i > start && arr[i] == arr[i - 1]) + continue; + if (arr[i] > target) + break; + templist.add(arr[i]); + backtrack(ans, templist, target - arr[i], i + 1, arr); + templist.remove(templist.size() - 1); + } + } + + public static void main(String args[]) { + int v[] = { 10, 1, 2, 7, 6, 1, 5 }; + List> comb = combinationalSumII(v, 8); + System.out.println(comb.toString().replace(",", " ")); + } +} diff --git a/backtracking/bt_prob5.class b/backtracking/bt_prob5.class new file mode 100644 index 0000000000000000000000000000000000000000..c50e9f36008f64cb999f4a6060491cfac337bed7 GIT binary patch literal 2115 zcma)6QBT`e6#lO5*uj{_g}Nx4QGR4tNy&pkQcIp6v2x&G(hH%9<&!ad%`eKj@*r%MYquj%WV2VwG;+hUMpI5 zqiss{Hoi!|T#>;z6;twpEgq@z$m1ZX?)m}4#cZYY%zf_8)ZAcerW`f>U@Omws^xIE zx#2zXIk|!L=$l3}T%Vifu^I+&PQkQ>8Qj!x9)lV#z@Qe1HiJ+pYPg6?3O>*P2nl0vfg<}|sS)MG$pfq^t8tH9hdr`Sn1^2iX zpE8UmUHZZEaL4PMNt?tYcOwd$dkP9PFr_fu*=;ar#USvSg__%HdBp68?h2h8ZP~wY zgKEudjkkgMULswd6Tp?dhIdAI_vExsDc`M0Cq==n)yjV4|8<3)h<`Hxg$g*f<-0S=f_L>ZuC3?%Tlct(aE7?4B86qTFr_7gdOy}rFj9V{Z zTaGwO_GQPMwWg(4$V`%P>jf0)CrIJ}0ferUB8JG5f-rfXp^smKc6OGbU7G%S9p`z0 zlz3nolHF#w2uqU=&U)t56!V= z4QZO>5)PcB`4m5kd6`S`7rE{z&ag6SQfs0}vLsAL=zxJajL;=AaR)Zt?g=aq%Lg$F z3Bm|Jp34|+GY|?;==dRA(bYd8uZg<)hq@+8OKXz2w3eb(rbnSCO^+^o{W!^;4P@#k8&*Lb>-V(&if)7W@V^`GO3_--^$LG**Q{JQl|AH4V@R djh#T(;6AM?jn)DU+$S_-6SPm${sukS{{WqgslNaK literal 0 HcmV?d00001 diff --git a/backtracking/bt_prob5.java b/backtracking/bt_prob5.java new file mode 100644 index 0000000..2fee04b --- /dev/null +++ b/backtracking/bt_prob5.java @@ -0,0 +1,94 @@ +/** + * find logest path in maze + * + */ + +class bt_prob5 { + private static boolean isSafe(int[][] mat, boolean[][] visited, int x, int y) { + return (x >= 0 && x < mat.length && y >= 0 && y < mat[0].length) && + mat[x][y] == 1 && !visited[x][y]; + } + + public static int findLongestPath(int mat[][], boolean[][] visited, int i, int j, int x, int y, int max_dist, + int dist) { + + if (mat[i][j] == 0) { + return 0; + } + + // base condition + if (i == x && j == y) { + return Math.max(dist, max_dist); + } + visited[i][j] = true; + + // go to the bottom cell + if (isSafe(mat, visited, i + 1, j)) { + max_dist = findLongestPath(mat, visited, i + 1, j, x, y, + max_dist, dist + 1); + } + + // go to the right cell + if (isSafe(mat, visited, i, j + 1)) { + max_dist = findLongestPath(mat, visited, i, j + 1, x, y, + max_dist, dist + 1); + } + + // go to the top cell + if (isSafe(mat, visited, i - 1, j)) { + max_dist = findLongestPath(mat, visited, i - 1, j, x, y, + max_dist, dist + 1); + } + + // go to the left cell + if (isSafe(mat, visited, i, j - 1)) { + max_dist = findLongestPath(mat, visited, i, j - 1, x, y, + max_dist, dist + 1); + } + + // backtrack: remove (i, j) from the visited matrix + visited[i][j] = false; + + return max_dist; + + } + + public static int findLongestPathLength(int[][] mat, int i, int j, int x, int y) { + // base case: invalid input + if (mat == null || mat.length == 0 || mat[i][j] == 0 || mat[x][y] == 0) { + return -1; + } + + // `M × N` matrix + int M = mat.length; + int N = mat[0].length; + + // construct an `M × N` matrix to keep track of visited cells + boolean[][] visited = new boolean[M][N]; + + // (i, j) are the source cell, and (x, y) are the destination + // cell coordinates + return findLongestPath(mat, visited, i, j, x, y, 0, 0); + } + + public static void main(String[] args) { + // input matrix + int mat[][] = { + { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, + { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, + { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, + { 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 }, + { 1, 0, 0, 0, 1, 1, 1, 1, 1, 1 }, + { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 }, + { 1, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, + { 1, 0, 1, 1, 1, 1, 0, 0, 1, 1 }, + { 1, 1, 0, 0, 1, 0, 0, 0, 0, 1 }, + { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 } + }; + + // (0, 0) are the source cell, and (5, 7) are the destination + // cell coordinates + int max_dist = findLongestPathLength(mat, 0, 0, 5, 7); + System.out.println("The maximum length path is " + max_dist); + } +} \ No newline at end of file diff --git a/backtracking/bt_prob6.class b/backtracking/bt_prob6.class new file mode 100644 index 0000000000000000000000000000000000000000..ecf514ef107b3d6c490e1c73b1c2d33350c1435f GIT binary patch literal 1704 zcmaJ>-EJF27(J6+@2(vuF=<@4wc9$76x(fLT1rZ56c8yDu9CWFD~ibltnF2^wY_WE zn@YLnjwe7MAyl5ATu@X&;F_o4K@j51tQ~Ji#D!F(R%8(!xY}ab%A+N64#2NTwL2M z?$qxJ^lJiVRC>qV0;cMGk3Gzu5?i)>HkQ7L8?rAO0xQ#EJ^xwIb;q|9m37Z)hr#f` z#JikS?f3Pcw>#|3O;uHPR|{!M8w+3>SLZ`#774M_Y`=1 zHlmxU#alX-*m8P3+Y8;AiQ59JC+a&bH-St4kHaz_MT(CF&^RreIIeTtUF4Soghb^f z#0wgn6Rw7G&XdF`qfMyD(3{}dkNL`BqW1#|h3LDqmM^@*4DjG5Xlp-1e^JTbD6D@w zF*bC$*BXVa{$=IxIhHDUX(|@=eu0snp3o}9P6+ILKW21delj9Izj3^bl+_!ukQr6T zeaOFvGb|#9^Eihh*JWHrnN|g>xX$$!s`!9!_~Qd%LMecJ5AQs-`VkoWxWO{|ic#ZCU^T literal 0 HcmV?d00001 diff --git a/backtracking/bt_prob6.java b/backtracking/bt_prob6.java new file mode 100644 index 0000000..8d7d8bb --- /dev/null +++ b/backtracking/bt_prob6.java @@ -0,0 +1,90 @@ +/** + * + * Find paths from corner cell to middle cell in maze + * + * Given a square maze containing positive numbers, find all paths from a corner + * cell (any of the extreme four corners) to the middle cell. We can move + * exactly n steps from a cell in 4 directions i.e. North, East, West and South + * where n is value of the cell, + * + * We can move to mat[i+n][j], mat[i-n][j], mat[i][j+n], and mat[i][j-n] from a + * cell mat[i][j] where n is value of mat[i][j]. + */ + +public class bt_prob6 { + + public static void printPath(int[][] maze, int i, int j, String ans) { + + // If we reach the center cell + if (i == maze.length / 2 && j == maze.length / 2) { + + // Make the final answer, Print the + // final answer and Return + ans += "(" + i + ", " + j + ") -> MID"; + System.out.println(ans); + return; + } + + // If the element at the current position + // in maze is 0, simply Return as it has + // been visited before. + if (maze[i][j] == 0) { + return; + } + + // If element is non-zero, then note + // the element in variable 'k' + int k = maze[i][j]; + + // Mark the cell visited by making the + // element 0. Don't worry, the element + // is safe in 'k' + maze[i][j] = 0; + + // Make recursive calls in all 4 + // directions pro-actively i.e. if the next + // cell lies in maze or not. Right call + if (j + k < maze.length) { + printPath(maze, i, j + k, ans + "(" + i + ", " + j + ") -> "); + } + + // down call + if (i + k < maze.length) { + printPath(maze, i + k, j, ans + "(" + i + ", " + j + ") -> "); + } + + // left call + if (j - k > 0) { + printPath(maze, i, j - k, ans + "(" + i + ", " + j + ") -> "); + } + + // up call + if (i - k > 0) { + printPath(maze, i - k, j, ans + "(" + i + ", " + j + ") -> "); + } + + // Unmark the visited cell by substituting + // its original value from 'k' + maze[i][j] = k; + } + + public static void main(String[] args) { + + // Creating the maze + int[][] maze = { + { 3, 5, 4, 4, 7, 3, 4, 6, 3 }, + { 6, 7, 5, 6, 6, 2, 6, 6, 2 }, + { 3, 3, 4, 3, 2, 5, 4, 7, 2 }, + { 6, 5, 5, 1, 2, 3, 6, 5, 6 }, + { 3, 3, 4, 3, 0, 1, 4, 3, 4 }, + { 3, 5, 4, 3, 2, 2, 3, 3, 5 }, + { 3, 5, 4, 3, 2, 6, 4, 4, 3 }, + { 3, 5, 1, 3, 7, 5, 3, 6, 4 }, + { 6, 2, 4, 3, 4, 5, 4, 5, 1 } + }; + + // Calling the printPath function + printPath(maze, 0, 0, ""); + } + +} diff --git a/backtracking/bt_prob7.class b/backtracking/bt_prob7.class new file mode 100644 index 0000000000000000000000000000000000000000..db5b4fbf12969d280c405e367a5e6bdbd6fd41f3 GIT binary patch literal 2523 zcmcIlOLN;)6#i~3M~TBhhHS6rH|BUN^1x)I8DJJp$*Vp+e)HDmW(V1 z!iq(Q6*C=R!;r}{@qOPpNBZsg<}Uy) z<5LBlh$@f}YepDx842-_RB#Nhh~1!!A+g5AjSNFL*G8U~6mq^ITwFi08g9Z>q}sqR zs^B_a7q=SgdK$R;TrW~WB!@|o>mIN0{(EnT!yiR&gqM|8I4=w{A2wr;Z@-jE7+T@%l*)EIiZc#9g1%`nGGVhNU%ZTaIDQv+imAPoq&Zw8y9e}iZ z%pJ>45vIC&b<8v}QpK_fa?DR^?~wQciMH~|ms_bgT8R|1s)Bb7q;3t}rXF;t6E$8+ zDOki3Ljya_aID0aw6tXwxHF?W3$&{^+!UkRe*kB{h+bQ7x7_X=48gLUyrJ_-^-~Ft;c(qv==VsB+D!nyF zZ&3XM?rVr$j#DdT&2RqlFKa1Z?CURy7dg!hBd0qWHCgXIacU)~ReWq)p6~vD)?Vpn zeJX8_um7u(?sO=lE2j7M3eY(qQN!&3_)@Ru16B9X!ss#Jh_2D17@Da6F)<`lUzeEBHdp{V=@t0h5QVm zRW!})eJPSOxJkMp(>_F36aAAFwBiuqY{ekjFp8r%MQ;OOtvKzvoFTIwoF!xe_@9I& zNb9#E^%|6{w@xIbbu^2_$>8>;(c2`Fo>726CN`l0>u3p#MiLu1#PA5?flE@ml!$EL za08wp>>c<0h}QaHyX3y!B$Qaikp~ic{Ldd`v5KP)0<{0B&hRQR0;wG$zG0HGi^S|9 zUJ2rP1%0@I^O(Q|`Z2tQFKGP|m+%#xeS=|_eFvoHNXrPzkl0^P*%mHtp*gIG&wwYy z*QAjs%VgX|Tcfg$_G`rJ3=HzfAo^ zV1Sw^N>_{sBmpem%l(Z*Qki7l#10R67_0Lru~1k{8Bi|D^f&utX> result, ArrayList nums, ArrayList output, + int index) { + if (index == nums.size()) { + result.add(output); + return; + } + + // do not current element include + findSubsets(result, nums, new ArrayList<>(output), index + 1); + + // include current element; + output.add(nums.get(index)); + findSubsets(result, nums, new ArrayList<>(output), index + 1); + + } + + public static subsets() + + public static void main(String[] args) { + + // Main List for storing all subsets + List> subset = new ArrayList<>(); + + // Input ArrayList + ArrayList input = new ArrayList<>(); + input.add(1); + input.add(2); + input.add(3); + + findSubsets(subset, input, new ArrayList<>(), 0); + + // Comparator is used so that all subset get + // sorted in ascending order of values + Collections.sort(subset, (o1, o2) -> { + int n = Math.min(o1.size(), o2.size()); + for (int i = 0; i < n; i++) { + if (o1.get(i) == o2.get(i)) { + continue; + } else { + return o1.get(i) - o2.get(i); + } + } + return 1; + }); + + // Printing Subset + for (int i = 0; i < subset.size(); i++) { + for (int j = 0; j < subset.get(i).size(); j++) { + System.out.print(subset.get(i).get(j) + " "); + } + System.out.println(); + } + + } +} diff --git a/backtracking/bt_prob8.class b/backtracking/bt_prob8.class new file mode 100644 index 0000000000000000000000000000000000000000..33773c54e601949f77970ad7b3aa519445c2eb92 GIT binary patch literal 1240 zcma)5YfsZq7=BLIty}3fK!yTN0dLznnKuM2phzTHGMvd2GWnn#D@$=}N!O9!SO17V zLHscA5`KU`%J`nHurc?+Gv@B3WNdw&1q%nsoOZpyfY z+x(1H0`Bl3#fNkR8K^uiE8{NaB;+LAV+bvomg%lA1XAfu264@<8VvD*X&J9tjf&yC z(JOU2k#|k2+H6&thRZOP+Rmp7d-{Q%Yq@4US1_Bd#t)V1_n zmx3#pkZ@nY13Z-QNWnZF^Y{e?i+G~oDKrU73YM{=U@g}< z_KY36#8?-M`$rw1SE~#O->;rnE&YyRq+7wiD+cL6ueXfiE*E{)5EpKfVWQXmHM?FX zY}2+pL&T=}iL9W`%TpsdM#Da!ZQ^374qfVr9towxrfW1P({2&(M8|H^&b=nDU2@#e z8dRUNtzkW!OSt(5iJOT#*lX?BEr3= zhsHyfDK$Xz#7_w2V+0ERyrE_@ffI=8*YosI3gtz@kO(V`%T#EbP6Tg7SMQhnjGz~} zp3I(pfs#?bBPd|&NX;haP7rEC+RAVg^%&u7QvASC)HWhwwGH{7U!1<+(VrzuAW95k zp6)p5og@(%`a4gOUJ{#0iU@$kePUBY@v3JB*QyaMf##{uFS#5Li)ArbEC)ly!Z!@5 aCs5jmcFl@;woH=JDXPjHy+)}5uKxvILKYJM literal 0 HcmV?d00001 diff --git a/backtracking/bt_prob8.java b/backtracking/bt_prob8.java new file mode 100644 index 0000000..c5c7632 --- /dev/null +++ b/backtracking/bt_prob8.java @@ -0,0 +1,30 @@ +import java.util.*; + +//find all subset +public class bt_prob8 { + public static List> findsubset(int nums[]) { + List> result = new ArrayList<>(); + ArrayList output = new ArrayList<>(); + subsetUtil(result, output, nums, 0); + return result; + } + + public static void subsetUtil(List> result, ArrayList output, int[] nums, int i) { + if (i == nums.length) { + result.add(output); + return; + } + output.add(nums[i]); + subsetUtil(result, new ArrayList<>(output), nums, i + 1); + output.remove(output.size() - 1); + subsetUtil(result, new ArrayList<>(output), nums, i + 1); + + } + + public static void main(String[] args) { + + int nums[] = { 1, 2, 3 }; + System.out.println(findsubset(nums)); + + } +} diff --git a/backtracking/bt_prob9.java b/backtracking/bt_prob9.java new file mode 100644 index 0000000..0ab76cf --- /dev/null +++ b/backtracking/bt_prob9.java @@ -0,0 +1,5 @@ +DHO8D8E66B2GFMDQ + +public class bt_prob9 { + +} diff --git a/bitsort.class b/bitsort.class new file mode 100644 index 0000000000000000000000000000000000000000..b7bd8f1947b6dbd78a45ab753dbb56302bcf354d GIT binary patch literal 3140 zcmcImX?GJ<7=CWEOgf!H(~|C@K$kQv6hRA;Ql$YTlD25E6>wpaOp~F>Ovp?M#a%&M z5X2RC#RV7is2@rT=O~}mpWqKskAm-=Oi0oe^ou7ackc48&-=W0=I1LHe*~}r--_r! zunPUy%!dI1cZzW0ER zC?9s$f?>Q0>+pbxJ=n`<`vg2Fq6t9{9^(2Bd+>+{`#q37hx8c{W6IG2tp+1+w9MLVLQXU)OsLDe)ER{A3ccF0DO%E3@GsOzR-X64L~VkY&tvDA&n zYVbHco~Xe_2~XlFuKu)yXYj0qqc|qvIUFa=qW64G5}xPIU%-oec!?~W@Ze<$Cvi%` zD>yCSRSB=*bqR0aG?k@Dn=RR_Jk7boz$nu<@fJ;@3>8tC$QX@TW1L23G#(>?wYXKl z83}LW9Rcr3cn|M02sT`0k&Q$TC^0fyU36xpU0Ym-O(iRvdX`~HaWfx`(@>94A*daw zHjacshJ608&2J0$y!{}9N7c+RIh7-E4+Rp^a~erINt#rJDSk3C!BAhWUZ6KwH@Njq zf4GDgw(&*%`HHcI^i+zHRCSHo(a9OJDCfsSe1H$H;PBS26%m$#X=#-o{*G{VdXF-LfG%6tTbz}tRP>G zy*s672{Xx1Y2>2BWolXr>9R`MeYc>3_P&UZah4dz7(+u^o>W4*7L(0!)lAaNFlCKj zb{p+H|D}^l;JoHmBKnMEw<;5IE=75jS-O4|N-SNYTArp>2tzVY+mV(JGr0U=i)@Ze zj^ifB<2=`e1~{Ijy*q7~N}3dOuI9_jt9tJ)f{|aMikzl`ScrLz+Jz8kmz_B~A)0yMg5|~A0Ub}svcBWkT zx4?Jgv%-q1gW}<_3G`b64}$dELVMfjyDow%BLmqw%h^f&K_7`8+CS~+zXWm51yl_ME|Lk%qMGtt!Z5sg4oexm5Otc=FiO+A$?52G zIr`i_cN3*tdlvmoPKVDugSsZC&+XhlgJl=t12zdhS5K4RurjK5*a$fZj)p$hQ8z(x zxra1d)_Ehr)57Ns{pYTpY&mZQ%WKhxY8q=OU@zrYN55s1ijPvL#{e2IhDIEu`5`pp z7+P=wtvH3{77ER9UO_Vxuuj1GD`*nn<&X^iPI`GbZX-BuCm(q_949Zl#yc;eiNI)% zbl0}bp|t|z-L*FrCd&(xn+ua$3X>J~WELwo|A1AkGiWQ4DnQ`_s|fElN~N8`?WC2T z2-Za*1SpvvgedHLu%<@j7o8o{N(!oiG{pdc-A(^E2d9*%brkd+v{!*mIL9UF^fP>o Y&*@A3Zd%vU$qteUlkJ_jpH9dA0g`hpjsO4v literal 0 HcmV?d00001 diff --git a/bitsort.java b/bitsort.java new file mode 100644 index 0000000..c0730dc --- /dev/null +++ b/bitsort.java @@ -0,0 +1,47 @@ +import java.util.*; + +public class bitsort { + + public static List sortByBits(List arr) { + int n = arr.size(); + for (int i = 0; i < n; i++) + arr.set(i, arr.get(i) + 10001 * Integer.bitCount(arr.get(i))); + Collections.sort(arr); + for (int i = 0; i < n; i++) + arr.set(i, arr.get(i) % 10001); + return arr; + } + + public static int longestStrChain(List words) { + int ans = 0; + Map dp = new HashMap<>(); + + Collections.sort(words, (a, b) -> a.length() - b.length()); + for (final String word : words) { + int bestLength = 0; + for (int i = 0; i < word.length(); ++i) { + final String pred = word.substring(0, i) + word.substring(i + 1); + bestLength = Math.max(bestLength, dp.getOrDefault(pred, 0) + 1); + } + dp.put(word, bestLength); + ans = Math.max(ans, bestLength); + } + + return ans; + } + + // ["a","b","ba","bca","bda","bdca"] + public static void main(String[] args) { + List list = new ArrayList<>(); + list.add("a"); + list.add("b"); + + list.add("ba"); + list.add("bca"); + list.add("bda"); + list.add("bdca"); + + int res = longestStrChain(list); + System.out.println(res); + } +}