├── README.md
├── TEMPLATE.md
├── adobe
├── README.md
├── amend-the-sentence.md
├── generate-parentheses.md
├── implement-atoi.md
├── kmax-cont-vowels.md
├── leaders-in-an-array.md
├── longest-arithmetic-progression.md
├── minimum-insertions-to-make-two-arrays-equal.md
├── most-recent-library.md
├── next-higher-palindromic-number-same-digit.md
├── pots-of-gold-game.md
├── smallest-range-covering-elements-from-k-lists.md
├── subarray-with-given-sum.md
├── subset-sum-problem.md
├── sum-of-power-of-natural-numbers.md
└── winner-of-an-election.md
├── amazon
├── README.md
├── brackets-in-matrix-chain-multiplication.md
├── burning-tree.md
├── column-name-from-a-given-column-number.md
├── count-ways-to-nth-stairorder-does-not-matter.md
├── delete-n-nodes-after-m-nodes-of-a-linked-list.md
├── first-non-repeating-character-in-a-stream.md
├── ipl-2021-match-day-2.md
├── is-sudoku-valid.md
├── longest-mountain-in-array.md
├── maximum-of-all-subarrays-of-size.md
├── maximum-profit.md
├── nuts-and-bolts-problem.md
├── phone-directory.md
├── rotting-oranges.md
└── serialize-and-deserialize-a-binary-tree.md
├── assets
├── gfg.svg
└── lc.svg
├── goldman-sachs
├── README.md
├── array-pair-sum-divisibility-problem3257.md
├── count-the-subarrays-having-product-less-than-k1708.md
├── decode-the-string2444.md
├── find-missing-and-repeating2512.md
├── find-the-position-of-m-th-item1723.md
├── greatest-common-divisor-of-strings.md
├── k-largest-elements3736.md
├── minimum-size-subarray-sum.md
├── number-following-a-pattern3126.md
├── overlapping-rectangles1924.md
├── print-anagrams-together.md
├── run-length-encoding.md
├── squares-in-nn-chessboard1801.md
├── total-decoding-messages1235.md
└── ugly-numbers2254.md
├── intuit
├── as-far-from-land-as-possible.md
├── capacity-to-ship-packages-within-d-days.md
├── construct-quad-tree.md
├── course-schedule-ii.md
├── find-in-mountain-array.md
├── koko-eating-bananas.md
├── largest-number-in-k-swaps.md
├── min-swaps-to-arrange-binary-grid.md
├── minimum-sum-partition.md
├── missing-no-in-string.md
├── number-of-boomerangs.md
├── number-of-provinces.md
├── pacific-atlantic-water-flow.md
├── split-array-largest-sum.md
└── word-search.md
├── microsoft
├── README.md
├── alien-dictionary.md
├── bridge-edge-in-graph.md
├── connect-nodes-at-same-level.md
├── count-number-of-subtrees-having-given-sum.md
├── find-all-four-sum-numbers.md
├── generate-binary-numbers.md
├── length-of-largest-region-of-1s.md
├── minimum-steps-to-destination.md
├── minimum-sum-partition.md
├── possible-words-from-phone-digits.md
├── prerequisite-tasks.md
├── rotate-by-90-degree.md
├── spirally-traversing-a-matrix.md
├── stickler-theif.md
└── stock-span-problem.md
└── walmart
├── divide-two-integers.md
├── find-array-given-subset-sums.md
├── find-the-kth-largest-integer-in-the-array.md
├── generate-random-point-in-a-circle.md
├── guess-number-higher-or-lower-ii.md
├── largest-number-in-k-swaps.md
├── maximum-height-tree.md
├── maximum-performance-of-a-team.md
├── number-of-unique-paths.md
├── path-with-maximum-probability.md
├── power-of-numbers.md
├── remove-colored-pieces-if-both-neighbors-are-the-same-color.md
├── sorted-subsequence-of-size-3.md
├── stone-game.md
└── transform-to-sum-tree.md
/README.md:
--------------------------------------------------------------------------------
1 | # 6 Companies 30 Days Challenge
2 |
3 | In this repo I am uploading my solutions for [6Companies30Days Challenge](https://www.youtube.com/watch?v=8ESo_bXhRC4) by [Arsh Goyal](https://www.linkedin.com/in/arshgoyal/)
4 |
5 | ## Problem Sets
6 |
7 |
8 | Goldman Sachs (15/15)
9 |
10 | Sr | [Problems](./goldman-sachs/README.md) | TryIt | Status
11 | ----|---------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------|---------
12 | 1 | [Print Anagrams Together](./goldman-sachs/print-anagrams-together.md) | [](https://practice.geeksforgeeks.org/problems/print-anagrams-together/1/#) | ✅
13 | 2 | [Overlapping Rectangles](./goldman-sachs/overlapping-rectangles1924.md) | [](https://practice.geeksforgeeks.org/problems/overlapping-rectangles1924/1/) | ✅
14 | 3 | [Count the subarrays having product less than k](./goldman-sachs/count-the-subarrays-having-product-less-than-k1708.md) | [](https://practice.geeksforgeeks.org/problems/count-the-subarrays-having-product-less-than-k1708/1/) | ✅
15 | 4 | [Run Length Encoding](./goldman-sachs/run-length-encoding.md) | [](https://practice.geeksforgeeks.org/problems/run-length-encoding/1/) | ✅
16 | 5 | [Ugly Number](./goldman-sachs/ugly-numbers2254.md) | [](https://practice.geeksforgeeks.org/problems/ugly-numbers2254/1/) | ✅
17 | 6 | [Greatest Common Divisor of Strings](./goldman-sachs/greatest-common-divisor-of-strings.md) | [](https://leetcode.com/problems/greatest-common-divisor-of-strings/) | ✅
18 | 7 | [Find the position of M-th item](./goldman-sachs/find-the-position-of-m-th-item1723.md) | [](https://practice.geeksforgeeks.org/problems/find-the-position-of-m-th-item1723/1#) | ✅
19 | 8 | [Total Decoding Messages](./goldman-sachs/total-decoding-messages1235.md) | [](https://practice.geeksforgeeks.org/problems/total-decoding-messages1235/1/) | ✅
20 | 9 | [Number following a pattern](./goldman-sachs/number-following-a-pattern3126.md) | [](https://practice.geeksforgeeks.org/problems/number-following-a-pattern3126/1#) | ✅
21 | 10 | [Max 10 numbers in a list having 10M entries](./goldman-sachs/k-largest-elements3736.md) | [](https://practice.geeksforgeeks.org/problems/k-largest-elements3736/1) | ✅
22 | 11 | [Find Missing And Repeating](./goldman-sachs/find-missing-and-repeating2512.md) | [](https://practice.geeksforgeeks.org/problems/find-missing-and-repeating2512/1/#) | ✅
23 | 12 | [Squares in N*N Chessboard](./goldman-sachs/squares-in-nn-chessboard1801.md) | [](https://practice.geeksforgeeks.org/problems/squares-in-nn-chessboard1801/1) | ✅
24 | 13 | [Decode the string](./goldman-sachs/decode-the-string2444.md) | [](https://practice.geeksforgeeks.org/problems/decode-the-string2444/1) | ✅
25 | 14 | [Minimum Size Subarray Sum](./goldman-sachs/minimum-size-subarray-sum.md) | [](https://leetcode.com/problems/minimum-size-subarray-sum/) | ✅
26 | 15 | [Array Pair Sum Divisibility Problem](./goldman-sachs/array-pair-sum-divisibility-problem3257.md) | [](https://practice.geeksforgeeks.org/problems/array-pair-sum-divisibility-problem3257/1#) | ✅
27 |
28 |
29 |
30 |
31 | Amazon (15/15)
32 |
33 | Sr | [Problems](./amazon/README.md) | TryIt | Status
34 | ----|---------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------|---------
35 | 1 | [Maximum Profit](./amazon/maximum-profit.md) | [](https://practice.geeksforgeeks.org/problems/maximum-profit4657/1) | ✅
36 | 2 | [Longest Mountain in Array](./amazon/longest-mountain-in-array.md) | [](https://leetcode.com/problems/longest-mountain-in-array/) | ✅
37 | 3 | [IPL 2021 - Match Day 2](./amazon/ipl-2021-match-day-2.md) | [](https://practice.geeksforgeeks.org/problems/deee0e8cf9910e7219f663c18d6d640ea0b87f87/1/) | ✅
38 | 4 | [Brackets in Matrix Chain Multiplication](./brackets-in-matrix-chain-multiplication.md) | [](https://practice.geeksforgeeks.org/problems/brackets-in-matrix-chain-multiplication1024/1/) | ✅
39 | 5 | [Phone directory](./amazon/phone-directory.md) | [](https://practice.geeksforgeeks.org/problems/phone-directory4628/1/) | ✅
40 | 6 | [Maximum of all subarrays of size k](./amazon/maximum-of-all-subarrays-of-size.md) | [](https://practice.geeksforgeeks.org/problems/maximum-of-all-subarrays-of-size-k3101/1) | ✅
41 | 7 | [First non-repeating character in a stream](./amazon/first-non-repeating-character-in-a-stream.md) | [](https://practice.geeksforgeeks.org/problems/first-non-repeating-character-in-a-stream1216/1) | ✅
42 | 8 | [Count ways to N'th Stair(Order does not matter)](./amazon/count-ways-to-nth-stairorder-does-not-matter.md) | [](https://practice.geeksforgeeks.org/problems/count-ways-to-nth-stairorder-does-not-matter1322/1/) | ✅
43 | 9 | [Is Sudoku Valid](./amazon/is-sudoku-valid.md) | [](https://practice.geeksforgeeks.org/problems/is-sudoku-valid4820/1/) | ✅
44 | 10 | [Nuts and Bolts Problem](./amazon/nuts-and-bolts-problem.md) | [](https://practice.geeksforgeeks.org/problems/nuts-and-bolts-problem0431/1) | ✅
45 | 11 | [Serialize and Deserialize a Binary Tree](./amazon/serialize-and-deserialize-a-binary-tree.md) | [](https://practice.geeksforgeeks.org/problems/serialize-and-deserialize-a-binary-tree/1) | ✅
46 | 12 | [Column name from a given column number](./amazon/column-name-from-a-given-column-number.md) | [](https://practice.geeksforgeeks.org/problems/column-name-from-a-given-column-number4244/1/) | ✅
47 | 13 | [Rotting Oranges](./amazon/rotting-oranges.md) | [](https://leetcode.com/problems/rotting-oranges/) | ✅
48 | 14 | [Burning Tree](./amazon/burning-tree.md) | [](https://practice.geeksforgeeks.org/problems/burning-tree/1/) | ✅
49 | 15 | [Delete N nodes after M nodes of a linked list](./amazon/delete-n-nodes-after-m-nodes-of-a-linked-list.md) | [](https://practice.geeksforgeeks.org/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/1/) | ✅
50 |
51 |
52 |
53 |
54 | Microsoft (15/15)
55 |
56 | Sr | [Problems](./microsoft/README.md) | TryIt | Status
57 | ----|--------------------------------------------------------------------------------------- |-------------------------------------------------------------------------------------------------------------------------------------------|---------
58 | 1 | [Minimum sum partition](./microsoft/minimum-sum-partition.md) | [](https://practice.geeksforgeeks.org/problems/minimum-sum-partition3317/1/) | ✅
59 | 2 | [Prerequisite Tasks](./microsoft/prerequisite-tasks.md) | [](https://practice.geeksforgeeks.org/problems/prerequisite-tasks/1/) | ✅
60 | 3 | [Rotate by 90 degree](./microsoft/rotate-by-90-degree.md) | [](https://practice.geeksforgeeks.org/problems/rotate-by-90-degree0356/1/) | ✅
61 | 4 | [Spirally traversing a matrix](./microsoft/spirally-traversing-a-matrix.md) | [](https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix-1587115621/1/) | ✅
62 | 5 | [Stock span problem](./microsoft/stock-span-problem.md) | [](https://practice.geeksforgeeks.org/problems/stock-span-problem-1587115621/1) | ✅
63 | 6 | [Possible Words From Phone Digits](./microsoft/possible-words-from-phone-digits.md) | [](https://practice.geeksforgeeks.org/problems/possible-words-from-phone-digits-1587115620/1/) | ✅
64 | 7 | [Unit Area of largest region of 1's](./microsoft/length-of-largest-region-of-1s.md) | [](https://practice.geeksforgeeks.org/problems/length-of-largest-region-of-1s-1587115620/1/) | ✅
65 | 8 | [Connect Nodes at Same Level](./microsoft/connect-nodes-at-same-level.md) | [](https://practice.geeksforgeeks.org/problems/connect-nodes-at-same-level/1/) | ✅
66 | 9 | [Count Number of SubTrees having given Sum](./microsoft/count-number-of-subtrees-having-given-sum.md) | [](https://practice.geeksforgeeks.org/problems/count-number-of-subtrees-having-given-sum/1/) | ✅
67 | 10 | [Stickler Thief](./microsoft/stickler-theif.md) | [](https://practice.geeksforgeeks.org/problems/stickler-theif-1587115621/1/) | ✅
68 | 11 | [Generate Binary Numbers](./microsoft/generate-binary-numbers.md) | [](https://practice.geeksforgeeks.org/problems/generate-binary-numbers-1587115620/1/) | ✅
69 | 12 | [Find All Four Sum Numbers](./microsoft/find-all-four-sum-numbers.md) | [](https://practice.geeksforgeeks.org/problems/find-all-four-sum-numbers1732/1) | ✅
70 | 13 | [Bridge edge in a graph](./microsoft/bridge-edge-in-graph.md) | [](https://practice.geeksforgeeks.org/problems/bridge-edge-in-graph/1) | ✅
71 | 14 | [Minimum steps to destination](./microsoft/minimum-steps-to-destination.md) | [](https://practice.geeksforgeeks.org/problems/minimum-number-of-steps-to-reach-a-given-number5234/1/) | ✅
72 | 15 | [Alien Dictionary](./microsoft/alien-dictionary.md) | [](https://practice.geeksforgeeks.org/problems/alien-dictionary/1/) | ✅
73 |
74 |
75 |
76 |
77 | Adobe (15/15)
78 |
79 | Sr | [Problems](./adobe/README.md) | TryIt | Status
80 | ----|-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------
81 | 1 | [Subarray with given sum](./adobe/subarray-with-given-sum.md) | [](https://practice.geeksforgeeks.org/problems/subarray-with-given-sum-1587115621/1) | ✅
82 | 2 | [Longest Arithmetic Progression](./adobe/longest-arithmetic-progression.md) | [](https://practice.geeksforgeeks.org/problems/longest-arithmetic-progression1019/1/) | ✅
83 | 3 | [No. of distict Words with k max contiguous vowels](./adobe/kmax-cont-vowels.md) | [](https://practice.geeksforgeeks.org/problems/7b9d245852bd8caf8a27d6d3961429f0a2b245f1/1/) | ✅
84 | 4 | [Partition Equal Subset Sum](./adobe/subset-sum-problem.md) | [](https://practice.geeksforgeeks.org/problems/subset-sum-problem2014/1) | ✅
85 | 5 | [Express as sum of power of natural numbers](./adobe/sum-of-power-of-natural-numbers.md) | [](https://practice.geeksforgeeks.org/problems/express-as-sum-of-power-of-natural-numbers5647/1) | ✅
86 | 6 | [Generate Parentheses](./adobe/generate-parentheses.md) | [](https://practice.geeksforgeeks.org/problems/generate-all-possible-parentheses/1/) | ✅
87 | 7 | [Pots of Gold Game](./adobe/pots-of-gold-game.md) | [](https://practice.geeksforgeeks.org/problems/pots-of-gold-game/1/) | ✅
88 | 8 | [Implement Atoi](./adobe/implement-atoi.md) | [](https://practice.geeksforgeeks.org/problems/implement-atoi/1/) | ✅
89 | 9 | [Next higher palindromic number using same digits](./adobe/next-higher-palindromic-number-same-digit.md) | [](https://practice.geeksforgeeks.org/problems/next-higher-palindromic-number-using-the-same-set-of-digits5859/1/) | ✅
90 | 10 | [Winner of an election](./adobe/winner-of-an-election.md) | [](https://practice.geeksforgeeks.org/problems/winner-of-an-election-where-votes-are-represented-as-candidate-names-1587115621/1/) | ✅
91 | 11 | [Amend The Sentence](./adobe/amend-the-sentence.md) | [](https://practice.geeksforgeeks.org/problems/amend-the-sentence3235/1) | ✅
92 | 12 | [Leaders in an array](./adobe/leaders-in-an-array.md) | [](https://practice.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1/) | ✅
93 | 13 | [Minimum operations to convert array A to B](./adobe/minimum-insertions-to-make-two-arrays-equal.md) | [](https://practice.geeksforgeeks.org/problems/minimum-insertions-to-make-two-arrays-equal/1/) | ✅
94 | 14 | [Smallest range in K lists](./adobe/smallest-range-covering-elements-from-k-lists.md) | [](https://practice.geeksforgeeks.org/problems/find-smallest-range-containing-elements-from-k-lists/1/) | ✅
95 | 15 | [Most Recent Library](./adobe/most-recent-library.md) | | ✅
96 |
97 |
98 |
99 |
100 | Intuit (15/15)
101 |
102 | Sr | Problems | TryIt | Status
103 | ----|---------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------|--------
104 | 1 | [Minimum sum partition](./intuit/minimum-sum-partition.md) | [](https://practice.geeksforgeeks.org/problems/minimum-sum-partition3317/1/) | ✅
105 | 2 | [Word Search](./intuit/word-search.md) | [](https://practice.geeksforgeeks.org/problems/word-search/1/) | ✅
106 | 3 | [Find the missing no in string](./intuit/missing-no-in-string.md) | [](https://practice.geeksforgeeks.org/problems/find-the-missing-no-in-string/1/) | ✅
107 | 4 | [Largest number in K swaps](./intuit/largest-number-in-k-swaps.md) | [](https://practice.geeksforgeeks.org/problems/largest-number-in-k-swaps-1587115620/1) | ✅
108 | 5 | [Split Array Largest Sum](./intuit/split-array-largest-sum.md) | [](https://leetcode.com/problems/split-array-largest-sum/) | ✅
109 | 6 | [Find in Mountain Array](./intuit/find-in-mountain-array.md) | [](https://leetcode.com/problems/find-in-mountain-array/) | ✅
110 | 7 | [Capacity To Ship Packages Within D Days](./intuit/capacity-to-ship-packages-within-d-days.md) | [](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/) | ✅
111 | 8 | [Number of Boomerangs](./intuit/number-of-boomerangs.md) | [](https://leetcode.com/problems/number-of-boomerangs/) | ✅
112 | 9 | [Pacific Atlantic Water Flow](./intuit/pacific-atlantic-water-flow.md) | [](https://leetcode.com/problems/pacific-atlantic-water-flow/) | ✅
113 | 10 | [Number of Provinces](./intuit/number-of-provinces.md) | [](https://leetcode.com/problems/number-of-provinces/) | ✅
114 | 11 | [Construct Quad Tree](./intuit/construct-quad-tree.md) | [](https://leetcode.com/problems/construct-quad-tree/) | ✅
115 | 12 | [Course Schedule II](./intuit/course-schedule-ii.md) | [](https://leetcode.com/problems/course-schedule-ii/) | ✅
116 | 13 | [Minimum Swaps to Arrange a Binary Grid](./intuit/min-swaps-to-arrange-binary-grid.md) | [](https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/) | ✅
117 | 14 | [As Far from Land as Possible](./intuit/as-far-from-land-as-possible.md) | [](https://leetcode.com/problems/as-far-from-land-as-possible/) | ✅
118 | 15 | [Koko Eating Bananas](./intuit/koko-eating-bananas.md) | [](https://leetcode.com/problems/koko-eating-bananas/) | ✅
119 |
120 |
121 |
122 |
123 |
124 | Walmart (15/15)
125 |
126 | Sr | Problems | TryIt | Status
127 | ----|---------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|--------
128 | 1 | [Path with Maximum Probability](./walmart/path-with-maximum-probability.md) | [](https://leetcode.com/problems/path-with-maximum-probability/) | ✅
129 | 2 | [Stone Game](./walmart/stone-game.md) | [](https://leetcode.com/problems/stone-game/) | ✅
130 | 3 | [Remove Colored Pieces if Both Neighbors are the Same Color](./walmart/remove-colored-pieces-if-both-neighbors-are-the-same-color.md) | [](https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/) | ✅
131 | 4 | [Number of Unique Paths](./walmart/number-of-unique-paths.md) | [](https://practice.geeksforgeeks.org/problems/number-of-unique-paths5339/1/) | ✅
132 | 5 | [Transform to Sum Tree](./walmart/transform-to-sum-tree.md) | [](https://practice.geeksforgeeks.org/problems/transform-to-sum-tree/1/) | ✅
133 | 6 | [Power Of Numbers](./walmart/power-of-numbers.md) | [](https://practice.geeksforgeeks.org/problems/power-of-numbers-1587115620/1/) | ✅
134 | 7 | [Sorted subsequence of size 3](./walmart/sorted-subsequence-of-size-3.md) | [](https://practice.geeksforgeeks.org/problems/sorted-subsequence-of-size-3/1/) | ✅
135 | 8 | [Maximum Height Tree](./walmart/maximum-height-tree.md) | [](https://practice.geeksforgeeks.org/problems/maximum-height-tree4803/1/) | ✅
136 | 9 | [Guess Number Higher or Lower II](./walmart/guess-number-higher-or-lower-ii.md) | [](https://leetcode.com/problems/guess-number-higher-or-lower-ii/) | ✅
137 | 10 | [Generate Random Point in a Circle](./walmart/generate-random-point-in-a-circle.md) | [](https://leetcode.com/problems/generate-random-point-in-a-circle/) | ✅
138 | 11 | [Maximum Performance of a Team](./walmart/maximum-performance-of-a-team.md) | [](https://leetcode.com/problems/maximum-performance-of-a-team/) | ✅
139 | 12 | [Find Array Given Subset Sums](./walmart/find-array-given-subset-sums.md) | [](https://leetcode.com/problems/find-array-given-subset-sums/) | ✅
140 | 13 | [Find the Kth Largest Integer in the Array](./walmart/find-the-kth-largest-integer-in-the-array.md) | [](https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/) | ✅
141 | 14 | [Largest number in K swaps](./walmart/largest-number-in-k-swaps.md) | [](https://practice.geeksforgeeks.org/problems/largest-number-in-k-swaps-1587115620/1/) | ✅
142 | 15 | [Divide Two Integers](./walmart/divide-two-integers.md) | [](https://leetcode.com/problems/divide-two-integers/) | ✅
143 |
144 |
--------------------------------------------------------------------------------
/TEMPLATE.md:
--------------------------------------------------------------------------------
1 | # Title
2 |
3 | [](link)
4 | [](link)
5 |
6 |
7 | ### Sample Input
8 | ```
9 |
10 | ```
11 | ### Sample Output
12 | ```
13 |
14 | ```
15 |
16 | ### Solution
17 | ```cpp
18 |
19 | ```
20 |
21 | ### Accepted
22 | [](link)
23 |
--------------------------------------------------------------------------------
/adobe/README.md:
--------------------------------------------------------------------------------
1 | # 6Companies30Days Challenge
2 | ## Adobe
3 |
4 | ### Solved Problems
5 | - [Subarray with given sum](./subarray-with-given-sum.md)
6 | - [Longest Arithmetic Progression](./longest-arithmetic-progression.md)
7 | - [Number of distict Words with k maximum contiguous vowels](kmax-cont-vowels.md)
8 | - [Partition Equal Subset Sum](./subset-sum-problem.md)
9 | - [Express as sum of power of natural numbers](./sum-of-power-of-natural-numbers.md)
10 | - [Generate Parentheses](./generate-parentheses.md)
11 | - [Pots of Gold Game](./pots-of-gold-game.md)
12 | - [Implement Atoi](./implement-atoi.md)
13 | - [Next higher palindromic number using the same set of digits](./next-higher-palindromic-number-same-digit.md)
14 | - [Winner of an election](./winner-of-an-election.md)
15 | - [Amend The Sentence](./amend-the-sentence.md)
16 | - [Leaders in an array](./leaders-in-an-array.md)
17 | - [Minimum operations to convert array A to B](./minimum-insertions-to-make-two-arrays-equal.md)
18 | - [Smallest range in K lists](./smallest-range-covering-elements-from-k-lists.md)
19 | - [Most Recent Library](./most-recent-library.md)
--------------------------------------------------------------------------------
/adobe/amend-the-sentence.md:
--------------------------------------------------------------------------------
1 | # Amend The Sentence
2 |
3 | [](https://practice.geeksforgeeks.org/problems/amend-the-sentence3235/1#)
4 |
5 | Given a string which is basically a sentence without spaces between words. However the first letter of every word is in uppercase. You need to print this sentence after following amendments:
6 |
7 | 1. Put a single space between these words
8 | 2. Convert the uppercase letters to lowercase.
9 |
10 | **Note:** The first character of the string can be both uppercase/lowercase.
11 |
12 |
13 | ### Sample Input
14 | ```
15 | BruceWayneIsBatman
16 | ```
17 | ### Sample Output
18 | ```
19 | bruce wayne is batman
20 | ```
21 |
22 | ### Solution
23 | ```cpp
24 | class Solution {
25 | public:
26 | string amendSentence (string s)
27 | {
28 | string ans = "";
29 | for(char c: s) {
30 | if(c >= 'A' && c <= 'Z') {
31 | if(ans.size()) {
32 | ans += ' ';
33 | }
34 | ans += (c - 'A' + 'a');
35 | }
36 | else {
37 | ans += c;
38 | }
39 | }
40 | return ans;
41 | }
42 | };
43 | ```
44 |
45 | ### Accepted
46 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=f3166f048edc0b6b73f01f3f14b81167&pid=702907&user=jhasuraj)
47 |
--------------------------------------------------------------------------------
/adobe/generate-parentheses.md:
--------------------------------------------------------------------------------
1 | # Generate Parentheses
2 |
3 | [](https://practice.geeksforgeeks.org/problems/generate-all-possible-parentheses/1/#)
4 |
5 | Given an integer N representing the number of pairs of parentheses, the task is to generate all combinations of well-formed(balanced) parentheses.
6 |
7 | ### Sample Input
8 | ```
9 | 3
10 | ```
11 | ### Sample Output
12 | ```
13 | ((()))
14 | (()())
15 | (())()
16 | ()(())
17 | ()()()
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | class Solution {
23 | public:
24 | void pattern(int n, int open, int close, string s, vector &ans) {
25 | if(open == n && close == n) {
26 | return ans.push_back(s);
27 | }
28 | if(open < n) {
29 | pattern(n, open + 1, close, s + '(', ans);
30 | }
31 | if(open > close) {
32 | pattern(n, open, close + 1, s + ')', ans);
33 | }
34 | }
35 |
36 | vector AllParenthesis(int n) {
37 | vector ans;
38 | pattern(n, 0, 0, "", ans);
39 | return ans;
40 | }
41 | };
42 | ```
43 |
44 | ### Accepted
45 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=a703d0e72585724ad446ae4d64033987&pid=702078&user=jhasuraj)
46 |
--------------------------------------------------------------------------------
/adobe/implement-atoi.md:
--------------------------------------------------------------------------------
1 | # Implement Atoi
2 |
3 | [](https://practice.geeksforgeeks.org/problems/implement-atoi/1/#)
4 |
5 | Your task is to implement the function atoi. The function takes a string(str) as argument and converts it to an integer and returns it.
6 |
7 | **Note:** You are not allowed to use inbuilt function.
8 |
9 | ### Sample Input
10 | ```
11 | 123
12 | ```
13 |
14 | ### Sample Output
15 | ```
16 | 123
17 | ```
18 |
19 | ### Solution
20 | ```cpp
21 | class Solution {
22 | public:
23 | int atoi(string str) {
24 | int num = 0, fact = 1;
25 | if(str[0] == '-') {
26 | fact = -1;
27 | str = str.substr(1);
28 | }
29 | for(char c: str) {
30 | if(c - '0' < 0 || c - '0' > 9) {
31 | num = -1;
32 | fact = 1;
33 | break;
34 | }
35 | num = num * 10 + c - '0';
36 | }
37 | return num * fact;
38 | }
39 | };
40 | ```
41 |
42 | ### Accepted
43 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=5e574a145f8c02018e51925409f67075&pid=700386&user=jhasuraj)
44 |
--------------------------------------------------------------------------------
/adobe/kmax-cont-vowels.md:
--------------------------------------------------------------------------------
1 | # Number of distict Words with k maximum contiguous vowels
2 |
3 | [](https://practice.geeksforgeeks.org/problems/7b9d245852bd8caf8a27d6d3961429f0a2b245f1/1/#)
4 |
5 | Find the number of unique words consisting of lowercase alphabets only of length N that can be formed with at-most K contiguous vowels.
6 |
7 | ### Hint
8 | 
9 |
10 |
11 | ### Sample Input
12 | ```
13 | 384 71
14 | ```
15 | ### Sample Output
16 | ```
17 | 233867288
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | class Solution {
23 | public:
24 | int kvowelwords(int N, int K) {
25 |
26 | long long int mod = 1000000007;
27 |
28 | vector> dp(N, vector(K + 1, 0));
29 | dp[0][0] = 21;
30 | long long int sum = 21;
31 |
32 | if(K > 0) {
33 | dp[0][1] = 5;
34 | sum += 5;
35 | };
36 |
37 | for(int n = 1; n < N; ++n) {
38 | sum = dp[n][0] = (sum * 21ll) % mod;
39 | for(int k = 1; k <= K; ++k) {
40 | sum += dp[n][k] = (dp[n - 1][k - 1]*5ll) % mod;
41 | sum %= mod;
42 | }
43 | }
44 |
45 | return sum;
46 | }
47 | };
48 | ```
49 |
50 | ### Accepted
51 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=622a9ee7a7bafca6b842bae328ed29d9&pid=706392&user=jhasuraj)
52 |
--------------------------------------------------------------------------------
/adobe/leaders-in-an-array.md:
--------------------------------------------------------------------------------
1 | # Leaders in an array
2 |
3 | [](https://practice.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1/#)
4 |
5 | Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader.
6 |
7 | ### Sample Input
8 | ```
9 | 6
10 | 16 17 4 3 5 2
11 | ```
12 | ### Sample Output
13 | ```
14 | 17 5 2
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution {
20 | public:
21 | vector leaders(int a[], int n){
22 | vector ans;
23 | ans.push_back(a[n-1]);
24 |
25 | int max_val = a[n-1];
26 |
27 | for(int i = 1; i < n; ++i){
28 | if(max_val <= a[n - i - 1]) {
29 | ans.push_back(a[n - i - 1]);
30 | max_val = a[n - i - 1];
31 | }
32 | }
33 |
34 | reverse(ans.begin(), ans.end());
35 |
36 | return ans;
37 | }
38 | };
39 | ```
40 |
41 | ### Accepted
42 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=30cfc513c6cf9858e5cc87d1b57fc621&pid=701210&user=jhasuraj)
43 |
--------------------------------------------------------------------------------
/adobe/longest-arithmetic-progression.md:
--------------------------------------------------------------------------------
1 | # Longest Arithmetic Progression
2 |
3 | [](https://practice.geeksforgeeks.org/problems/longest-arithmetic-progression1019/1/#)
4 |
5 | Given an array called A[] of sorted integers having no duplicates, find the length of the Longest Arithmetic Progression (LLAP) in it.
6 |
7 | ### Sample Input
8 | ```
9 | 6
10 | 1 7 10 13 14 19
11 | ```
12 |
13 | ### Sample Output
14 | ```
15 | 4
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution {
21 | public:
22 | int lengthOfLongestAP(int A[], int n) {
23 |
24 | if(n == 1) return 1;
25 | if(n == 2) return 2;
26 |
27 | int ans = 2;
28 |
29 | vector> dp(n, vector(n, 2));
30 |
31 | for(int x = n - 2; x > 0; --x) {
32 | int i = x - 1;
33 | int j = x + 1;
34 |
35 | while(i >= 0 && j < n) {
36 | if(A[i] + A[j] == 2 * A[x]) {
37 | dp[i][x] = dp[x][j] + 1;
38 | ans = max(ans, dp[i][x]);
39 | --i;
40 | ++j;
41 | }
42 | else if(A[i] + A[j] < 2 * A[x]) {
43 | ++j;
44 | }
45 | else {
46 | --i;
47 | }
48 | }
49 | }
50 |
51 | return ans;
52 | }
53 | };
54 | ```
55 | ### Knapsack (TLE)
56 | ```cpp
57 | class Solution {
58 | public:
59 | int AP_SIZE(int A[], int n, bitset<1000> selection) {
60 |
61 | int last_num, dif, size = 0;
62 |
63 | for(int i = 0; i < n; ++i) {
64 | if(size == 0 && selection[i]) {
65 | ++size;
66 | last_num = A[i];
67 | }
68 | else if(size == 1 && selection[i]) {
69 | ++size;
70 | dif = A[i] - last_num;
71 | last_num = A[i];
72 | }
73 | else if(size > 1 && selection[i]) {
74 | if(dif == A[i] - last_num) {
75 | ++size;
76 | dif = A[i] - last_num;
77 | last_num = A[i];
78 | }
79 | else {
80 | return 0;
81 | }
82 | }
83 | }
84 | return size;
85 | }
86 |
87 | int max_size(int A[], int n, int i, bitset<1000> selection, vector, int>>& cache) {
88 |
89 | if(i >= n) {
90 | return AP_SIZE(A, n, selection);
91 | }
92 | if(cache[i].count(selection)) return cache[i][selection];
93 |
94 | bitset<1000> new_selection = selection;
95 | new_selection[i] = 1;
96 |
97 | return cache[i][selection] = max(max_size(A, n, i + 1, selection, cache), max_size(A, n, i + 1, new_selection, cache));
98 | }
99 |
100 | int lengthOfLongestAP(int A[], int n) {
101 | bitset<1000> selection(0);
102 | vector, int>> cache(1000);
103 | return max_size(A, n, 0, selection, cache);
104 | }
105 | };
106 | ```
107 |
108 | ### Accepted
109 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=92ef52d252cd3e098d536a2ff94977fb&pid=703290&user=jhasuraj)
--------------------------------------------------------------------------------
/adobe/minimum-insertions-to-make-two-arrays-equal.md:
--------------------------------------------------------------------------------
1 | # Minimum operations to convert array A to B
2 |
3 | [](https://practice.geeksforgeeks.org/problems/minimum-insertions-to-make-two-arrays-equal/1/#)
4 |
5 | Given two Arrays **A[]** and **B[]** of length **N** and **M** respectively. Find the minimum number of **insertions** and **deletions** on the array A[], required to make both the arrays identical.
6 |
7 | **Note:** Array B[] is sorted and all its elements are distinct, operations can be performed at any index not necessarily at end.
8 |
9 | ### Sample Input
10 | ```
11 | 1
12 | 5 3
13 | 1 2 5 3 1
14 | 1 3 5
15 | ```
16 |
17 | ### Sample Output
18 | ```
19 | 4
20 | ```
21 |
22 | ### Solution
23 | ```cpp
24 | class Solution {
25 | public:
26 | int lengthOfLIS(vector& nums) {
27 | if(nums.size() == 0) return 0;
28 |
29 | vector seq;
30 | seq.push_back(nums[0]);
31 |
32 | for(int i = 1; i < nums.size(); ++i) {
33 | if(seq.back() < nums[i]) {
34 | seq.push_back(nums[i]);
35 | continue;
36 | }
37 | int index = lower_bound(seq.begin(), seq.end(), nums[i]) - seq.begin();
38 | seq[index] = nums[i];
39 | }
40 | return seq.size();
41 | }
42 |
43 | int minInsAndDel(int A[], int B[], int N, int M) {
44 | vector MA;
45 | bitset<100001> availabe;
46 |
47 | for(int i = 0; i < M; ++i) {
48 | availabe.set(B[i]);
49 | }
50 |
51 | for(int i = 0; i < N; ++i) {
52 | if(availabe[A[i]]) {
53 | MA.push_back(A[i]);
54 | }
55 | }
56 | int lis = lengthOfLIS(MA);
57 | return (N + M - lis*2);
58 | }
59 | };
60 | ```
61 |
62 | ### 2D - DP (Memory Limit Exceeded)
63 | ```cpp
64 | class Solution {
65 | public:
66 | int minEditDistance(int A[], int B[], int& N, int& M, int a, int b, vector> &cache) {
67 | if(a == N) return M - b;
68 | if(b == M) return N - a;
69 | if(cache[a][b] != -1) return cache[a][b];
70 |
71 | if(A[a] == B[b]) {
72 | return cache[a][b] = minEditDistance(A, B, N, M, a+1, b+1, cache);
73 | }
74 | else {
75 | return cache[a][b] = min({
76 | minEditDistance(A, B, N, M, a+1, b, cache) + 1,
77 | minEditDistance(A, B, N, M, a, b+1, cache) + 1,
78 | minEditDistance(A, B, N, M, a+1, b+1, cache) + 2
79 | });
80 | }
81 | }
82 |
83 | int minInsAndDel(int A[], int B[], int N, int M) {
84 | vector> cache(N+1, vector(M+1, -1));
85 | return minEditDistance(A, B, N, M, 0, 0, cache);
86 | }
87 | };
88 | ```
89 |
90 | ### Accepted
91 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=9bf4ff89ca1f88a081a9b24e346f47d6&pid=706334&user=jhasuraj)
92 |
--------------------------------------------------------------------------------
/adobe/most-recent-library.md:
--------------------------------------------------------------------------------
1 | # Most Recent Library
2 |
3 | Given two library versions of an executable: for example, "10.1.1.3" and "10.1.1.9" or "10" and "10.1". Find out which one is more recent? Strings can be empty also.
4 |
5 | ### Sample Input
6 | ```
7 | 2
8 | 10.1.1.3
9 | 10.1.1.9
10 | ```
11 | ### Sample Output
12 | ```
13 | 10.1.1.9
14 | ```
15 |
16 | ### Solution
17 | ```cpp
18 | #include
19 | using namespace std;
20 |
21 | int main() {
22 |
23 | int n;
24 | cin >> n;
25 |
26 | vector> V(n);
27 |
28 | for (int i = 0; i < n; ++i) {
29 | string version;
30 | cin >> version;
31 | V[i].push_back(0);
32 | for(char c: version) {
33 | if(c == '.')
34 | V[i].push_back(0);
35 | else
36 | V[i].back() = V[i].back()*10 + c - '0';
37 | }
38 | }
39 |
40 | sort(V.begin(), V.end());
41 |
42 | bool dot = false;
43 |
44 | for(auto n: V.back()) {
45 | if(dot) cout << ".";
46 | cout << n;
47 | dot = true;
48 | }
49 |
50 | return 0;
51 | }
52 | ```
53 |
--------------------------------------------------------------------------------
/adobe/next-higher-palindromic-number-same-digit.md:
--------------------------------------------------------------------------------
1 | # Next higher palindromic number using the same set of digits
2 |
3 | Given a palindromic number N in the form of string. The task is to find the smallest palindromic number greater than N using the same set of digits as in N.
4 |
5 | [](https://practice.geeksforgeeks.org/problems/next-higher-palindromic-number-using-the-same-set-of-digits5859/1/#)
6 |
7 | ### Sample Input
8 | ```
9 | 1
10 | 454121454
11 | ```
12 |
13 | ### Sample Output
14 | ```
15 | 514424415
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution {
21 | public:
22 |
23 | string nextPalin(string N) {
24 | int len = N.size();
25 |
26 | if(len <= 3) {
27 | return "-1";
28 | }
29 |
30 | int mid = len/2;
31 |
32 | int first_small = -1;
33 |
34 | for(int i = mid - 1; i > 0; --i) {
35 | if(N[i-1] < N[i]){
36 | first_small = i-1;
37 | break;
38 | }
39 | }
40 |
41 | if(first_small < 0) {
42 | return "-1";
43 | }
44 |
45 | int later_small = first_small + 1;
46 | for(int i = later_small; i < mid; ++i) {
47 | if(N[later_small] > N[i] && N[i] > N[first_small]) {
48 | later_small = i;
49 | }
50 | }
51 |
52 | swap(N[later_small], N[first_small]);
53 | swap(N[len - later_small - 1], N[len - first_small - 1]);
54 |
55 | sort(N.begin() + first_small + 1, N.begin() + mid);
56 | sort(N.rbegin() + first_small + 1, N.rbegin() + mid);
57 |
58 | return N;
59 | }
60 | };
61 | ```
62 |
63 | ### Accepted
64 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=e6aeaec93727164cc195a1a0d58aa5d8&pid=703481&user=jhasuraj)
--------------------------------------------------------------------------------
/adobe/pots-of-gold-game.md:
--------------------------------------------------------------------------------
1 | # Pots of Gold Game
2 |
3 | [](https://practice.geeksforgeeks.org/problems/pots-of-gold-game/1/#)
4 |
5 | Two players X and Y are playing a game in which there are pots of gold arranged in a line, each containing some gold coins. They get alternating turns in which the player can pick a pot from one of the ends of the line. The winner is the player who has a higher number of coins at the end. The objective is to maximize the number of coins collected by X, assuming Y also plays optimally.
6 |
7 | Return the maximum coins X could get while playing the game. Initially, X starts the game.
8 |
9 | ### Sample Input
10 | ```
11 | 4
12 | 8 15 3 7
13 | ```
14 |
15 | ### Sample Output
16 | ```
17 | 22
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | class Solution {
23 | public:
24 | int maxCoins(vector&A,int n, int start, int end, vector>& cache) {
25 |
26 | if(end < start) {
27 | return 0;
28 | }
29 | if(end == start) {
30 | return A[end];
31 | }
32 | if(cache[start][end] != -1) return cache[start][end];
33 |
34 | return cache[start][end] = max({
35 | A[start] + min(maxCoins(A, n, start + 2, end, cache), maxCoins(A, n, start + 1, end - 1, cache)),
36 | A[end] + min(maxCoins(A, n, start, end - 2, cache), maxCoins(A, n, start + 1, end - 1, cache))
37 | });
38 | }
39 | int maxCoins(vector&A,int n)
40 | {
41 | vector> cache(n, vector(n, -1));
42 | return maxCoins(A, n, 0, n-1, cache);
43 | }
44 | };
45 | ```
46 |
47 | ### Accepted
48 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=9e35a87b0b5f934277144b50627eeaec&pid=700428&user=jhasuraj)
49 |
--------------------------------------------------------------------------------
/adobe/smallest-range-covering-elements-from-k-lists.md:
--------------------------------------------------------------------------------
1 | # Smallest range in K lists
2 |
3 | [](https://practice.geeksforgeeks.org/problems/find-smallest-range-containing-elements-from-k-lists/1/#)
4 |
5 | Given K sorted lists of integers, KSortedArray[] of size N each. The task is to find the smallest range that includes at least one element from each of the K lists. If more than one such range's are found, return the first such range found.
6 |
7 | ### Sample Input
8 | ```
9 | 5 3
10 | 1 3 5 7 9
11 | 0 2 4 6 8
12 | 2 3 5 7 11
13 | ```
14 |
15 | ### Sample Output
16 | ```
17 | 1 2
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | #define pipi pair>
23 | class Solution {
24 | public:
25 | pair findSmallestRange(int KSortedArray[][N], int n, int k)
26 | {
27 | priority_queue, greater> minheap;
28 |
29 | int low = INT_MAX, high = INT_MIN;
30 | for(int i = 0; i < k; ++i) {
31 | int val = KSortedArray[i][0];
32 | low = min(low, val);
33 | high = max(high, val);
34 | minheap.push({val, {i, 0} });
35 | }
36 |
37 | int range = high - low;
38 | int max_value = high;
39 | int min_value = low;
40 |
41 | while(true) {
42 | pipi min_entry = minheap.top(); minheap.pop();
43 |
44 | int new_row = min_entry.second.first;
45 | int new_col = min_entry.second.second + 1;
46 | if(new_col >= n) break;
47 |
48 | int new_val = KSortedArray[new_row][new_col];
49 | minheap.push({new_val, {new_row, new_col}});
50 |
51 | min_value = minheap.top().first;
52 | max_value = max(max_value, new_val);
53 |
54 | if(max_value - min_value < range) {
55 | low = min_value;
56 | high = max_value;
57 | range = high - low;
58 | }
59 | }
60 |
61 | return {low, high};
62 | }
63 | };
64 | ```
65 |
66 | ### Accepted
67 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=b0ca0e6990a7903142a197b365a7a265&pid=700497&user=jhasuraj)
68 |
--------------------------------------------------------------------------------
/adobe/subarray-with-given-sum.md:
--------------------------------------------------------------------------------
1 | # Subarray with given sum
2 |
3 | [](https://practice.geeksforgeeks.org/problems/subarray-with-given-sum-1587115621/1#)
4 |
5 | Given an unsorted array A of size N that contains only non-negative integers, find a continuous sub-array which adds to a given number S.
6 |
7 | ### Sample Input
8 | ```
9 | 5 12
10 | 1 2 3 7 5
11 | ```
12 | ### Sample Output
13 | ```
14 | 2 4
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution {
20 | public:
21 | vector subarraySum(int arr[], int n, long long s) {
22 |
23 | int left = 0, right = 0;
24 | long long sum = (long long) arr[0];
25 | int changed = true;
26 |
27 | while(changed) {
28 | changed = false;
29 | while(left < n && sum > s) {
30 | sum -= (long long) arr[left];
31 | ++left;
32 | changed = true;
33 | }
34 | while(right < n - 1 && sum < s) {
35 | ++right;
36 | sum += (long long) arr[right];
37 | changed = true;
38 | }
39 | if(sum == s) {
40 | break;
41 | }
42 | }
43 |
44 | if(sum == s) {
45 | vector ans(2, 0);
46 | ans[0] = left + 1;
47 | ans[1] = right + 1;
48 | return ans;
49 | }
50 | else {
51 | vector ans(1, -1);
52 | return ans;
53 | }
54 | }
55 | };
56 | ```
57 |
58 | ### Accepted
59 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=3778e89d9233ab281349b66e10679d68&pid=701236&user=jhasuraj)
60 |
--------------------------------------------------------------------------------
/adobe/subset-sum-problem.md:
--------------------------------------------------------------------------------
1 | # Partition Equal Subset Sum
2 |
3 | [](https://practice.geeksforgeeks.org/problems/subset-sum-problem2014/1#)
4 |
5 | Given an array arr[] of size N, check if it can be partitioned into two parts such that the sum of elements in both parts is the same.
6 |
7 | ### Sample Input
8 | ```
9 | 4
10 | 1 5 11 5
11 | ```
12 |
13 | ### Sample Output
14 | ```
15 | YES
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution {
21 | public:
22 | int equalPartition(int N, int arr[])
23 | {
24 | sort(arr, arr+N);
25 |
26 | int sum = accumulate(arr, arr + N, 0);
27 |
28 | if(sum & 1) return 0;
29 |
30 | int half = sum/2;
31 |
32 | vector< vector > dp(N + 1, vector(half + 1, 0));
33 |
34 | for(int i = 0; i < N; ++i) {
35 | for(int j = 1; j <= half; ++j) {
36 | if(j < arr[i]) {
37 | dp[i+1][j] = dp[i][j];
38 | continue;
39 | }
40 | dp[i+1][j] = max({arr[i], dp[i][j - arr[i]] + arr[i], dp[i][j]});
41 | }
42 | }
43 |
44 | return half == dp.back().back();
45 | }
46 | };
47 | ```
48 |
49 | ### Accepted
50 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=79146ffebcac12b5415bb299da721cbf&pid=704573&user=jhasuraj)
51 |
--------------------------------------------------------------------------------
/adobe/sum-of-power-of-natural-numbers.md:
--------------------------------------------------------------------------------
1 | # Express as sum of power of natural numbers
2 |
3 | [](https://practice.geeksforgeeks.org/problems/express-as-sum-of-power-of-natural-numbers5647/1#)
4 |
5 | Given two numbers n and x, find out the total number of ways n can be expressed as sum of xth power of unique natural numbers.As total number of ways can be very large ,so return the number of ways modulo 109 + 7.
6 |
7 | ### Sample Input
8 | ```
9 | 1
10 | 10 2
11 | ```
12 |
13 | ### Sample Output
14 | ```
15 | 1
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution {
21 | public:
22 | long long int mod = 1e9+7;
23 | long long int dp[1001][1002];
24 | long long int count(int n, int x, int k)
25 | {
26 | if(n == 0) return 1;
27 | if(n < 0) return 0;
28 | if(k > n) return 0;
29 |
30 | if(dp[n][k] != -1) return dp[n][k];
31 |
32 | long long int ans = count(n - pow(k, x), x, k + 1) + count(n, x, k + 1);
33 |
34 | dp[n][k] = ans %= mod;
35 |
36 | return ans;
37 | }
38 |
39 | int numOfWays(int n, int x)
40 | {
41 | memset(dp, -1, sizeof(dp));
42 | return count(n, x, 1);
43 | }
44 | };
45 | ```
46 |
47 | ### Accepted
48 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=10d297f717e185552ea45f41da740c21&pid=705641&user=jhasuraj)
--------------------------------------------------------------------------------
/adobe/winner-of-an-election.md:
--------------------------------------------------------------------------------
1 | # Winner of an election
2 |
3 | [](...problem...)
4 |
5 | Given an array of names (consisting of lowercase characters) of candidates in an election. A candidate name in array represents a vote casted to the candidate. Print the name of candidate that received Max votes. If there is tie, print lexicographically smaller name.
6 |
7 | ### Sample Input
8 | ```
9 | 13
10 | john johnny jackie johnny john jackie jamie jamie john johnny jamie johnny john
11 | ```
12 | ### Sample Output
13 | ```
14 | john 4
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution {
20 | public:
21 | vector winner(string arr[],int n)
22 | {
23 | unordered_map votes;
24 |
25 | for(int i = 0; i < n; ++i) {
26 | ++votes[arr[i]];
27 | }
28 |
29 | unordered_map> rank;
30 |
31 | int max_vote = 0;
32 | for(auto candidate: votes) {
33 | if(candidate.second >= max_vote) {
34 | max_vote = candidate.second;
35 | rank[max_vote].push_back(candidate.first);
36 | }
37 | }
38 |
39 | sort(rank[max_vote].begin(), rank[max_vote].end());
40 |
41 | return {rank[max_vote][0], to_string(max_vote)};
42 | }
43 | };
44 | ```
45 |
46 | ### Accepted
47 | [](...solution...)
48 |
--------------------------------------------------------------------------------
/amazon/README.md:
--------------------------------------------------------------------------------
1 | # 6Companies30Days Challenge
2 | ## Amazon
3 |
4 | ### Solved Problems
5 |
6 | - [Maximum Profit](./maximum-profit.md)
7 | - [Longest Mountain in Array](./longest-mountain-in-array.md)
8 | - [IPL 2021 - Match Day 2](./ipl-2021-match-day-2.md)
9 | - [Brackets in Matrix Chain Multiplication](./brackets-in-matrix-chain-multiplication.md)
10 | - [Phone directory](./phone-directory.md)
11 | - [Maximum of all subarrays of size k](./maximum-of-all-subarrays-of-size.md)
12 | - [First non-repeating character in a stream](./first-non-repeating-character-in-a-stream.md)
13 | - [Count ways to N'th Stair(Order does not matter)](./count-ways-to-nth-stairorder-does-not-matter.md)
14 | - [Is Sudoku Valid ](./is-sudoku-valid.md)
15 | - [Nuts and Bolts Problem](./nuts-and-bolts-problem.md)
16 | - [Serialize and Deserialize a Binary Tree](./serialize-and-deserialize-a-binary-tree.md)
17 | - [Column name from a given column number](./column-name-from-a-given-column-number.md)
18 | - [Rotting Oranges](./rotting-oranges.md)
19 | - [Burning Tree](./burning-tree.md)
20 | - [Delete N nodes after M nodes of a linked list](./delete-n-nodes-after-m-nodes-of-a-linked-list.md)
--------------------------------------------------------------------------------
/amazon/brackets-in-matrix-chain-multiplication.md:
--------------------------------------------------------------------------------
1 | # Brackets in Matrix Chain Multiplication
2 |
3 | [](https://practice.geeksforgeeks.org/problems/brackets-in-matrix-chain-multiplication1024/1/#)
4 |
5 | Given an array p[] of length n used to denote the dimensions of a series of matrices such that dimension of i'th matrix is p[i] * p[i+1]. There are a total of n-1 matrices. Find the most efficient way to multiply these matrices together.
6 | The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications such that you need to perform minimum number of multiplications. There are many options to multiply a chain of matrices because matrix multiplication is associative i.e. no matter how one parenthesize the product, the result will be the same.
7 |
8 | ### Sample Input
9 | ```
10 | 5
11 | 1 2 3 4 5
12 | ```
13 | ### Sample Output
14 | ```
15 | (((AB)C)D)
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | #define pis pair
21 |
22 | class Solution{
23 | public:
24 | string matrixChainOrder(int A[], int n){
25 |
26 | vector> DP(n-1, vector(n-1));
27 |
28 | for(int i = 0; i < n-1; ++i) {
29 | string M = "";
30 | M += (char) ('A' + i);
31 | DP[i][i] = { 0, M };
32 | }
33 |
34 |
35 | for(int size = 1; size <= n; ++size) {
36 | int l = 0;
37 | int m = size;
38 |
39 | while(m < n-1) {
40 |
41 | DP[l][m].first = numeric_limits::max();
42 |
43 | for(int i = l; i < m; ++i) {
44 | int operations = DP[l][i].first + DP[i+1][m].first + A[l]*A[i+1]*A[m+1];
45 |
46 | if(DP[l][m].first > operations) {
47 | DP[l][m].second = "(" + DP[l][i].second + DP[i+1][m].second + ")";
48 | DP[l][m].first = operations;
49 | }
50 |
51 | }
52 |
53 | ++l;
54 | ++m;
55 | }
56 | }
57 |
58 | return DP[0].back().second;
59 | }
60 | };
61 | ```
62 |
63 | ### Accepted
64 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=9b85d4c8a879148be735610bcf007721&pid=705397&user=jhasuraj)
65 |
--------------------------------------------------------------------------------
/amazon/burning-tree.md:
--------------------------------------------------------------------------------
1 | # Burning Tree
2 |
3 | [](https://practice.geeksforgeeks.org/problems/burning-tree/1/#)
4 |
5 | Given a binary tree and a node called target. Find the minimum time required to burn the complete binary tree if the target is set on fire. It is known that in 1 second all nodes connected to a given node get burned. That is its left child, right child, and parent.
6 |
7 | ### Sample Input
8 | ```
9 | 1 2 3 4 5 N 6 N N 7 8 N 9 N N N N N 10
10 | 8
11 | ```
12 | ### Sample Output
13 | ```
14 | 7
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution {
20 | public:
21 | int minTime(Node* root, int target)
22 | {
23 | unordered_map parent;
24 |
25 | //find target
26 | queue q1;
27 | q1.push(root);
28 |
29 | Node* node;
30 |
31 | while(!q1.empty()) {
32 | node = q1.front();
33 | q1.pop();
34 |
35 | if(node->data == target) {
36 | break;
37 | }
38 |
39 | if(node->left != NULL) {
40 | parent[node->left] = node;
41 | q1.push(node->left);
42 | }
43 |
44 | if(node->right != NULL) {
45 | parent[node->right] = node;
46 | q1.push(node->right);
47 | }
48 | }
49 |
50 | // find largest dist
51 | queue q2;
52 | q2.push(node);
53 | q2.push(NULL);
54 |
55 | unordered_map queued;
56 | int dist = -1;
57 |
58 | while(!q2.empty()) {
59 |
60 | node = q2.front();
61 | q2.pop();
62 |
63 | if(node == NULL) {
64 | ++dist;
65 | if(!q2.empty()) {
66 | q2.push(NULL);
67 | }
68 | continue;
69 | }
70 |
71 | if(node->left != NULL && !queued.count(node->left)) {
72 | q2.push(node->left);
73 | queued[node->left] = true;
74 | }
75 |
76 | if(node->right != NULL && !queued.count(node->right)) {
77 | q2.push(node->right);
78 | queued[node->right] = true;
79 | }
80 |
81 | if(parent.count(node) && !queued.count(parent[node])) {
82 | q2.push(parent[node]);
83 | queued[parent[node]] = true;
84 | }
85 | }
86 |
87 | return dist;
88 | }
89 | };
90 | ```
91 |
92 | ### Accepted
93 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=27145b0cafb4eebc74d3d7c237f48942&pid=702131&user=jhasuraj)
94 |
--------------------------------------------------------------------------------
/amazon/column-name-from-a-given-column-number.md:
--------------------------------------------------------------------------------
1 | # Column name from a given column number
2 |
3 | [](https://practice.geeksforgeeks.org/problems/column-name-from-a-given-column-number4244/1/#)
4 |
5 | Given a positive integer, return its corresponding column title as appear in an Excel sheet.
6 |
7 | Excel columns has a pattern like A, B, C, … ,Z, AA, AB, AC,…. ,AZ, BA, BB, … ZZ, AAA, AAB ….. etc. In other words, column 1 is named as “A”, column 2 as “B”, column 27 as “AA” and so on.
8 |
9 | ### Sample Input
10 | ```
11 | 28
12 | ```
13 | ### Sample Output
14 | ```
15 | AB
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution{
21 | public:
22 | string colName (long long int n)
23 | {
24 | string ans;
25 |
26 | while(n) {
27 | ans += (char) ('A' + (n-1) % 26);
28 | n = (n-1)/26;
29 | }
30 |
31 | reverse(ans.begin(), ans.end());
32 |
33 | return ans;
34 | }
35 | };
36 | ```
37 |
38 | ### Accepted
39 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=b6b1fdf3d26d74a8be26883c95f7443a&pid=702959&user=jhasuraj)
40 |
--------------------------------------------------------------------------------
/amazon/count-ways-to-nth-stairorder-does-not-matter.md:
--------------------------------------------------------------------------------
1 | # Count ways to N'th Stair(Order does not matter)
2 |
3 | [](https://practice.geeksforgeeks.org/problems/count-ways-to-nth-stairorder-does-not-matter1322/1/#)
4 |
5 | There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter).
6 |
7 | **Note:** Order does not matter means for n=4 {1 2 1},{2 1 1},{1 1 2} are considered same.
8 |
9 | ### Hint
10 | ```
11 | n = 2i + j;
12 |
13 | 4 = 2(0) + 4
14 | 4 = 2(1) + 2
15 | 4 = 2(2) + 0
16 | ```
17 |
18 | ### Sample Input
19 | ```
20 | 4
21 | ```
22 | ### Sample Output
23 | ```
24 | 3
25 | ```
26 |
27 | ### Solution
28 | ```cpp
29 | class Solution
30 | {
31 | public:
32 | long long countWays(int m)
33 | {
34 | return m/2 + 1ll;
35 | }
36 | };
37 | ```
38 |
39 | ### Accepted
40 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=8304d762c9435b549cbc78bd4048142e&pid=701419&user=jhasuraj)
41 |
--------------------------------------------------------------------------------
/amazon/delete-n-nodes-after-m-nodes-of-a-linked-list.md:
--------------------------------------------------------------------------------
1 | # Delete N nodes after M nodes of a linked list
2 |
3 | [](https://practice.geeksforgeeks.org/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/1/#)
4 |
5 | Given a linked list, delete N nodes after skipping M nodes of a linked list until the last of the linked list.
6 |
7 | #### Input:
8 |
9 | First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the linked list and next M and N respectively space separated. The last line contains the elements of the linked list.
10 |
11 | #### Output:
12 |
13 | Function should not print any output to stdin/console.
14 |
15 | #### User Task:
16 |
17 | The task is to complete the function linkdelete() which should modify the linked list as required.
18 |
19 | ### Sample Input
20 | ```
21 | 2
22 | 8
23 | 2 1
24 | 9 1 3 5 9 4 10 1
25 | 6
26 | 1 2
27 | 8 4 8 10 1 3
28 | ```
29 | ### Sample Output
30 | ```
31 | 9 1 5 9 10 1
32 | 8 10
33 | ```
34 |
35 | ### Solution
36 | ```cpp
37 | class Solution
38 | {
39 | public:
40 | void linkdelete(struct Node *head, int M, int N)
41 | {
42 | Node* node = head;
43 |
44 | while(node != NULL) {
45 | for(int i = 1; i < M && node != NULL; ++i) {
46 | node = node->next;
47 | }
48 |
49 | if(node == NULL) return;
50 |
51 | Node* ref = node;
52 |
53 | for(int i = 0; i <= N && node != NULL; ++i) {
54 | node = node->next;
55 | }
56 |
57 | ref->next = node;
58 |
59 | }
60 | }
61 | };
62 | ```
63 |
64 | ### Accepted
65 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=e43f1cb34ef47f0369f9454d37b9b699&pid=700021&user=jhasuraj)
66 |
--------------------------------------------------------------------------------
/amazon/first-non-repeating-character-in-a-stream.md:
--------------------------------------------------------------------------------
1 | # First non-repeating character in a stream
2 |
3 | [](https://practice.geeksforgeeks.org/problems/first-non-repeating-character-in-a-stream1216/1#)
4 |
5 | Given an input stream of A of n characters consisting only of lower case alphabets. The task is to find the first non repeating character, each time a character is inserted to the stream. If there is no such character then append '#' to the answer.
6 |
7 | ### Sample Input
8 | ```
9 | zzabbc
10 | ```
11 | ### Sample Output
12 | ```
13 | z#aaaa
14 | ```
15 |
16 | ### Solution
17 | ```cpp
18 | class Solution {
19 | public:
20 | string FirstNonRepeating(string A){
21 |
22 | // non repeating characters queue
23 | queue nrcq;
24 | vector used(26, false);
25 |
26 | string ans = "";
27 |
28 | for(int i = 0; i < A.size(); ++i) {
29 | char c = A[i];
30 | char output;
31 |
32 | if(used[c - 'a'] < 1) {
33 | nrcq.push(c);
34 | }
35 | ++used[c - 'a'];
36 |
37 | while(!nrcq.empty() && used[nrcq.front() - 'a'] > 1) {
38 | nrcq.pop();
39 | }
40 |
41 | if(nrcq.empty()) {
42 | output = '#';
43 | }
44 | else {
45 | output = nrcq.front();
46 | }
47 | ans += output;
48 | }
49 | return ans;
50 | }
51 | };
52 | ```
53 |
54 | ### Accepted
55 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=34c5bef29fc8c889ba9433ae7d76cb4f&pid=705333&user=jhasuraj)
56 |
--------------------------------------------------------------------------------
/amazon/ipl-2021-match-day-2.md:
--------------------------------------------------------------------------------
1 | # IPL 2021 - Match Day 2
2 |
3 | [](https://practice.geeksforgeeks.org/problems/deee0e8cf9910e7219f663c18d6d640ea0b87f87/1/#)
4 |
5 | Due to the rise of covid-19 cases in India, this year BCCI decided to organize knock-out matches in IPL rather than a league.
6 |
7 | Today is matchday 2 and it is between the most loved team Chennai Super Kings and the most underrated team - Punjab Kings. Stephen Fleming, the head coach of CSK, analyzing the batting stats of Punjab. He has stats of runs scored by all N players in the previous season and he wants to find the maximum score for each and every contiguous sub-list of size K to strategize for the game.
8 |
9 | ### Sample Input
10 | ```
11 | 9 3
12 | 1 2 3 1 4 5 2 3 6
13 | ```
14 | ### Sample Output
15 | ```
16 | 3 3 4 5 5 5 6
17 | ```
18 |
19 | ### Solution
20 | ```cpp
21 | class Solution {
22 | public:
23 | vector max_of_subarrays(vector arr, int n, int k) {
24 |
25 | priority_queue> MAXQ;
26 |
27 | for(int i = 0; i < k; ++i) {
28 | MAXQ.push({arr[i], i});
29 | }
30 |
31 | vectorans;
32 | ans.push_back(MAXQ.top().first);
33 |
34 | for(int i = k; i < n; ++i) {
35 | MAXQ.push({arr[i], i});
36 |
37 | while(!MAXQ.empty() && MAXQ.top().second <= i - k) {
38 | MAXQ.pop();
39 | }
40 |
41 | ans.push_back(MAXQ.top().first);
42 | }
43 |
44 | return ans;
45 | }
46 | };
47 | ```
48 |
49 | ### Accepted
50 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=d0ce9ea64d23cd3d9ea701d62d76a039&pid=707042&user=jhasuraj)
51 |
--------------------------------------------------------------------------------
/amazon/is-sudoku-valid.md:
--------------------------------------------------------------------------------
1 | # Is Sudoku Valid
2 |
3 | [](https://practice.geeksforgeeks.org/problems/is-sudoku-valid4820/1/#)
4 |
5 | Given an incomplete Sudoku configuration in terms of a 9x9 2-D square matrix(mat[][]) the task to check if the current configuration is valid or not where a 0 represents an empty block.
6 |
7 | **Note:** Current valid configuration does not ensure validity of the final solved sudoku.
8 |
9 | Refer to this : https://en.wikipedia.org/wiki/Sudoku
10 |
11 | ### Sample Input
12 | ```
13 | 3 0 6 5 0 8 4 0 0
14 | 5 2 0 0 0 0 0 0 0
15 | 0 8 7 0 0 0 0 3 1
16 | 0 0 3 0 1 0 0 8 0
17 | 9 0 0 8 6 3 0 0 5
18 | 0 5 0 0 9 0 6 0 0
19 | 1 3 0 0 0 0 2 5 0
20 | 0 0 0 0 0 0 0 7 4
21 | 0 0 5 2 0 6 3 0 0
22 | ```
23 | ### Sample Output
24 | ```
25 | 1
26 | ```
27 |
28 | ### Solution
29 | ```cpp
30 | class Solution{
31 | public:
32 | int isValid(vector> mat){
33 |
34 | // row, col, block cache
35 | vector> rowc(9), colc(9), bloc(9);
36 |
37 | for(int r = 0; r < 9; ++r) {
38 | for(int c = 0; c < 9; ++c) {
39 | int num = mat[r][c];
40 |
41 | if(
42 | num && (
43 | rowc[r].test(num) ||
44 | colc[c].test(num) ||
45 | bloc[3*(r/3) + c/3].test(num))
46 | ) return 0;
47 |
48 | rowc[r].set(num);
49 | colc[c].set(num);
50 | bloc[3*(r/3) + c/3].set(num);
51 | }
52 |
53 | }
54 | return 1;
55 | }
56 | };
57 | ```
58 |
59 | ### Accepted
60 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=066bfa3e462dabebf51f08ab533006ec&pid=705293&user=jhasuraj)
61 |
--------------------------------------------------------------------------------
/amazon/longest-mountain-in-array.md:
--------------------------------------------------------------------------------
1 | # Longest Mountain in Array
2 |
3 | [](https://leetcode.com/problems/longest-mountain-in-array/)
4 |
5 | You may recall that an array arr is a mountain array if and only if:
6 |
7 | - arr.length >= 3
8 | - There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
9 | - arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
10 | - arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
11 |
12 | Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.
13 |
14 | ### Example 1
15 | ```
16 | Input: arr = [2,1,4,7,3,2,5]
17 | Output: 5
18 | ```
19 | ### Example 2
20 | ```
21 | Input: arr = [2,2,2]
22 | Output: 0
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 | bool isLocalMin(vector& arr, int index) {
30 | int lastIndex = arr.size() - 1;
31 |
32 | if(index == 0) {
33 | return arr[0] < arr[1];
34 | }
35 | else if(index == lastIndex) {
36 | return arr[lastIndex - 1] > arr[lastIndex];
37 | }
38 | else {
39 | return arr[index - 1] >= arr[index] && arr[index] <= arr[index + 1];
40 | }
41 | }
42 | bool isLocalMax(vector& arr, int index) {
43 | int lastIndex = arr.size() - 1;
44 |
45 | if(index == 0) {
46 | return arr[0] > arr[1];
47 | }
48 | else if(index == lastIndex) {
49 | return arr[lastIndex - 1] < arr[lastIndex];
50 | }
51 | else {
52 | return arr[index - 1] < arr[index] && arr[index] > arr[index + 1];
53 | }
54 | }
55 | int longestMountain(vector& arr) {
56 |
57 | if(arr.size() < 3) return 0;
58 |
59 | int ans = 0;
60 | int lastLocalMin = -1;
61 | int lastLocalMax = -1;
62 |
63 | for(int i = 0; i < arr.size(); ++i) {
64 | if(isLocalMin(arr, i)) {
65 | if(lastLocalMin >= 0 && lastLocalMin < lastLocalMax && lastLocalMax < i) {
66 | ans = max(ans, i - lastLocalMin + 1);
67 | }
68 | lastLocalMin = i;
69 | }
70 | else if(isLocalMax(arr, i)) {
71 | lastLocalMax = i;
72 | }
73 | }
74 |
75 | return ans;
76 | }
77 | };
78 | ```
79 |
80 | ### Accepted
81 | [](https://leetcode.com/submissions/detail/614306576/)
82 |
--------------------------------------------------------------------------------
/amazon/maximum-of-all-subarrays-of-size.md:
--------------------------------------------------------------------------------
1 | # Maximum of all subarrays of size k
2 |
3 | [](https://practice.geeksforgeeks.org/problems/maximum-of-all-subarrays-of-size-k3101/1#)
4 |
5 | Given an array arr[] of size N and an integer K. Find the maximum for each and every contiguous subarray of size K.
6 |
7 | ### Sample Input
8 | ```
9 | 9 3
10 | 1 2 3 1 4 5 2 3 6
11 | ```
12 | ### Sample Output
13 | ```
14 | 3 3 4 5 5 5 6
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution
20 | {
21 | public:
22 | vector max_of_subarrays(int *arr, int n, int k)
23 | {
24 | priority_queue> MAXQ;
25 |
26 | for(int i = 0; i < k; ++i) {
27 | MAXQ.push({arr[i], i});
28 | }
29 |
30 | vectorans;
31 | ans.push_back(MAXQ.top().first);
32 |
33 | for(int i = k; i < n; ++i) {
34 | MAXQ.push({arr[i], i});
35 |
36 | while(!MAXQ.empty() && MAXQ.top().second <= i - k) {
37 | MAXQ.pop();
38 | }
39 |
40 | ans.push_back(MAXQ.top().first);
41 | }
42 |
43 | return ans;
44 | }
45 | };
46 | ```
47 |
48 | ### Accepted
49 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=f51db7b68b8bbbf5f7b26a63716bbc8a&pid=701349&user=jhasuraj)
50 |
--------------------------------------------------------------------------------
/amazon/maximum-profit.md:
--------------------------------------------------------------------------------
1 | # Maximum Profit
2 |
3 | [](https://practice.geeksforgeeks.org/problems/maximum-profit4657/1#)
4 |
5 | In the stock market, a person buys a stock and sells it on some future date. Given the stock prices of N days in an array A[ ] and a positive integer K, find out the maximum profit a person can make in at-most K transactions. A transaction is equivalent to (buying + selling) of a stock and new transaction can start only when the previous transaction has been completed.
6 |
7 | ### DP Table (Hint)
8 | 
9 |
10 | ### Sample Input
11 | ```
12 | 2
13 | 6
14 | 10 22 5 75 65 80
15 | ```
16 | ### Sample Output
17 | ```
18 | 87
19 | ```
20 |
21 | ### Solution
22 | ```cpp
23 | class Solution {
24 | public:
25 | int maxProfit(int K, int N, int A[]) {
26 |
27 | // DP of Transaction Count vs Price
28 | vector> TP(K+1, vector(N+1, 0));
29 |
30 | for(int t = 1; t <= K; ++t) {
31 | for(int p = 1; p <= N; ++p) {
32 | TP[t][p] = TP[t][p - 1];
33 | for(int i = 0; i < p; ++i) {
34 | TP[t][p] = max(TP[t][p], TP[t-1][i] + A[p-1] - A[i]);
35 | }
36 | }
37 | }
38 | return TP.back().back();
39 | }
40 | };
41 | ```
42 |
43 | ### Accepted
44 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=dc89596439fffc05b04dac11f8183b05&pid=704532&user=jhasuraj)
45 |
--------------------------------------------------------------------------------
/amazon/nuts-and-bolts-problem.md:
--------------------------------------------------------------------------------
1 | # Nuts and Bolts Problem
2 |
3 | [](https://practice.geeksforgeeks.org/problems/nuts-and-bolts-problem0431/1#)
4 |
5 | Given a set of N nuts of different sizes and N bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently.
6 |
7 | Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with nut to see which one is bigger/smaller.
8 |
9 | The elements should follow the following order ! # $ % & * @ ^ ~ .
10 |
11 | ### Sample Input
12 | ```
13 | 5
14 | @ % $ # ^
15 | % @ # $ ^
16 | ```
17 | ### Sample Output
18 | ```
19 | # $ % @ ^
20 | # $ % @ ^
21 | ```
22 |
23 | ### Solution
24 | ```cpp
25 | class Solution {
26 | public:
27 |
28 | void matchPairs(char nuts[], char bolts[], int n) {
29 |
30 | // align nuts and bolts
31 | for(int i = 0; i < n; ++i) {
32 | for(int j = i; j < n; ++j) {
33 | if(bolts[j] == nuts[i]) {
34 | char temp = bolts[i];
35 | bolts[i] = bolts[j];
36 | bolts[j] = temp;
37 | continue;
38 | }
39 | }
40 | }
41 |
42 | // find original position in an array
43 | vector order(n);
44 | iota(order.begin(), order.end(), 0);
45 | sort(order.begin(), order.end(), [&](int i, int j) {
46 | return nuts[i] < bolts[j];
47 | });
48 |
49 | // place nuts and bolts on its original position
50 | for(int i = 0; i < n; ++i) {
51 | nuts[i] = bolts[order[i]];
52 | }
53 | for(int j = 0; j < n; ++j) {
54 | bolts[j] = nuts[j];
55 | }
56 |
57 | }
58 | };
59 | ```
60 |
61 | ### Accepted
62 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=c65327e32ba6ef9d9f3c9741244ef0b3&pid=703024&user=jhasuraj)
63 |
--------------------------------------------------------------------------------
/amazon/phone-directory.md:
--------------------------------------------------------------------------------
1 | # Phone directory
2 |
3 | [](https://practice.geeksforgeeks.org/problems/phone-directory4628/1/#)
4 |
5 | Given a list of contacts contact[] of length n where each contact is a string which exist in a phone directory and a query string s. The task is to implement a search query for the phone directory. Run a search query for each prefix p of the query string s (i.e. from index 1 to |s|) that prints all the distinct contacts which have the same prefix as p in lexicographical increasing order. Please refer the explanation part for better understanding.
6 |
7 | **Note:** If there is no match between query and contacts, print "0".
8 |
9 | ### Sample Input
10 | ```
11 | 3
12 | geeikistest geeksforgeeks geeksfortest
13 | geeips
14 | ```
15 |
16 | ### Sample Output
17 | ```
18 | geeikistest geeksforgeeks geeksfortest
19 | geeikistest geeksforgeeks geeksfortest
20 | geeikistest geeksforgeeks geeksfortest
21 | geeikistest
22 | 0
23 | 0
24 | ```
25 |
26 | ### Solution
27 | ```cpp
28 |
29 | class TrieNode {
30 | public:
31 |
32 | TrieNode* child[26];
33 | char value;
34 | int ends, depth;
35 |
36 | TrieNode(char letter, int d) {
37 | value = letter;
38 | ends = 0;
39 | depth = d;
40 |
41 | for(int i = 0; i < 26; ++i) {
42 | child[i] = NULL;
43 | }
44 | }
45 | };
46 |
47 | class Trie {
48 | public:
49 |
50 | TrieNode* root;
51 |
52 | Trie() {
53 | root = new TrieNode('/', 0);
54 | }
55 |
56 | void insert(string& word) {
57 | TrieNode* node = root;
58 |
59 | for(int i = 0; i < word.size(); ++i) {
60 | int index = word[i] - 'a';
61 |
62 | if(node->child[index] == NULL)
63 | node->child[index] = new TrieNode(word[i], i + 1);
64 |
65 | node = node->child[index];
66 | }
67 |
68 | node->ends += 1;
69 | }
70 |
71 | vector wordsWithPrefix(string prefix) {
72 | TrieNode* node = root;
73 | vector results;
74 |
75 | int N = prefix.length();
76 | for(int i = 0; i < N; ++i) {
77 | node = node->child[prefix[i] - 'a'];
78 | if(node == NULL) return results;
79 | }
80 | TrieNode* prefix_end = node;
81 |
82 | stack nodes;
83 | nodes.push(node);
84 | string stream = "";
85 |
86 | while(!nodes.empty()) {
87 | node = nodes.top();
88 | nodes.pop();
89 |
90 | if(stream.size() > node->depth - prefix_end->depth) {
91 | stream = stream.substr(0, node->depth - prefix_end->depth);
92 | }
93 |
94 | stream += node->value;
95 | for(int i = 25; i >= 0; --i) {
96 | if(node->child[i] != NULL) {
97 | nodes.push(node->child[i]);
98 | }
99 | }
100 |
101 | if(node->ends) {
102 | results.push_back(prefix + stream.substr(1));
103 | }
104 | }
105 |
106 | return results;
107 | }
108 | };
109 |
110 | class Solution{
111 | public:
112 | vector> displayContacts(int n, string contact[], string s)
113 | {
114 | Trie* dict = new Trie();
115 | for(int i = 0; i < n; ++i) {
116 | dict->insert(contact[i]);
117 | }
118 |
119 | vector> ans(s.size());
120 |
121 | for(int i = 0; i < s.size(); ++i) {
122 | vector res = dict->wordsWithPrefix(s.substr(0, i + 1));
123 | if(res.empty()) {
124 | ans[i] = {"0"};
125 | }
126 | else {
127 | ans[i] = res;
128 | }
129 | }
130 | return ans;
131 | }
132 | };
133 | ```
134 |
135 | ### Accepted
136 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=2713a1cc4a767ddebf46383218bc9689&pid=705602&user=jhasuraj)
137 |
--------------------------------------------------------------------------------
/amazon/rotting-oranges.md:
--------------------------------------------------------------------------------
1 | # Rotting Oranges
2 |
3 | [](https://leetcode.com/problems/rotting-oranges/)
4 |
5 | You are given an `m x n` grid where each cell can have one of three values:
6 |
7 | - `0` representing an empty cell,
8 | - `1` representing a fresh orange, or
9 | - `2` representing a rotten orange.
10 |
11 | Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
12 |
13 | Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return `-1`.
14 |
15 |
16 |
17 | ### Example 1
18 | ```
19 | Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
20 | Output: 4
21 | ```
22 | ### Example 2
23 | ```
24 | Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
25 | Output: -1
26 | ```
27 |
28 | ### Solution
29 | ```cpp
30 | class Solution {
31 | public:
32 | int orangesRotting(vector>& grid) {
33 |
34 | int M = grid.size();
35 | int N = grid[0].size();
36 |
37 | // store all the fresh mangoes
38 | vector> initially_fresh;
39 |
40 | // store mangoes to be rotten in next sec;
41 | queue> decay_queue;
42 |
43 | // queued
44 | vector> queued(M, vector(N, false));
45 |
46 |
47 | for(int i = 0; i < M; ++i) {
48 | for(int j = 0; j < N; ++j) {
49 | if(grid[i][j] == 1) {
50 | initially_fresh.push_back({i, j});
51 | }
52 | else if(grid[i][j] == 2) {
53 | decay_queue.push({i, j});
54 | }
55 | }
56 | }
57 | decay_queue.push({-1, -1});
58 |
59 | int sec = -1;
60 |
61 | while(!decay_queue.empty()) {
62 | pair pos = decay_queue.front();
63 | decay_queue.pop();
64 |
65 | int y = pos.first;
66 | int x = pos.second;
67 |
68 | if(x == -1 && y == -1) {
69 | ++sec;
70 | if(!decay_queue.empty()) {
71 | decay_queue.push({-1, -1});
72 | }
73 | continue;
74 | }
75 |
76 | // left
77 | if(x > 0 && !queued[y][x-1] && grid[y][x-1] == 1) {
78 | queued[y][x-1] = true;
79 | decay_queue.push({y, x-1});
80 | }
81 |
82 | // right
83 | if(x < N - 1 && !queued[y][x+1] && grid[y][x+1] == 1) {
84 | queued[y][x+1] = true;
85 | decay_queue.push({y, x+1});
86 | }
87 |
88 | // top
89 | if(y > 0 && !queued[y-1][x] && grid[y-1][x] == 1) {
90 | queued[y-1][x] = true;
91 | decay_queue.push({y-1, x});
92 | }
93 |
94 | // bottom
95 | if(y < M - 1 && !queued[y+1][x] && grid[y+1][x] == 1) {
96 | queued[y+1][x] = true;
97 | decay_queue.push({y+1, x});
98 | }
99 | }
100 |
101 | for(auto pos: initially_fresh) {
102 | if(!queued[pos.first][pos.second]) {
103 | return -1;
104 | }
105 | }
106 |
107 | return sec;
108 | }
109 | };
110 | ```
111 |
112 | ### Accepted
113 | [](https://leetcode.com/submissions/detail/616169791/)
114 |
--------------------------------------------------------------------------------
/amazon/serialize-and-deserialize-a-binary-tree.md:
--------------------------------------------------------------------------------
1 | # Serialize and Deserialize a Binary Tree
2 |
3 | [](https://practice.geeksforgeeks.org/problems/serialize-and-deserialize-a-binary-tree/1#)
4 |
5 | Serialization is to store a tree in an array so that it can be later restored and Deserialization is reading tree back from the array. Now your task is to complete the function serialize which stores the tree into an array A[ ] and deSerialize which deserializes the array to the tree and returns it.
6 |
7 | **Note:** The structure of the tree must be maintained. Multiple nodes can have the same data.
8 |
9 | ### Sample Input
10 | ```
11 | 1 2 3
12 | ```
13 | ### Sample Output
14 | ```
15 | 2 1 3
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution
21 | {
22 | public:
23 | vector serialize(Node *root)
24 | {
25 | if(root == NULL) {
26 | return {};
27 | }
28 |
29 | vector left = serialize(root->left);
30 | vector right = serialize(root->right);
31 |
32 | vector ans;
33 |
34 | // preallocate memory
35 | ans.reserve(left.size() + right.size() + 1);
36 | ans.insert(ans.end(), left.begin(), left.end());
37 | ans.push_back(root->data);
38 | ans.insert(ans.end(), right.begin(), right.end());
39 |
40 | return ans;
41 | }
42 |
43 | Node * deSerialize(vector &A)
44 | {
45 | int N = A.size();
46 |
47 | if(N == 1) {
48 | Node* root = new Node(A[0]);
49 | return root;
50 | }
51 | if(N == 2) {
52 | Node* left = new Node(A[0]);
53 | Node* root = new Node(A[1]);
54 | root->left = left;
55 | return root;
56 | }
57 |
58 | Node* left = new Node(A[0]);
59 | Node* root = new Node(A[1]);
60 | Node* right = new Node(A[2]);
61 |
62 | root->left = left;
63 | root->right = right;
64 |
65 | for(int i = 3; i < N; i += 2) {
66 | Node* new_root = new Node(A[i]);
67 | Node* new_right = i == N-1 ? NULL : new Node(A[i + 1]);
68 |
69 | new_root->left = root;
70 | new_root->right = new_right;
71 |
72 | root = new_root;
73 | }
74 |
75 | return root;
76 | }
77 | };
78 | ```
79 |
80 | ### Accepted
81 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=3c5d82802df6e9e0e7ab4b6a9a4210cb&pid=700281&user=jhasuraj)
82 |
--------------------------------------------------------------------------------
/assets/gfg.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/assets/lc.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/goldman-sachs/README.md:
--------------------------------------------------------------------------------
1 | # 6Companies30Days Challenge
2 | ## Goldman Sachs
3 |
4 | ### Solved Problems
5 | - [Print Anagrams Together](./print-anagrams-together.md)
6 | - [Overlapping Rectangles](./overlapping-rectangles1924.md)
7 | - [Count the subarrays having product less than k](./count-the-subarrays-having-product-less-than-k1708.md)
8 | - [Run Length Encoding](./run-length-encoding.md)
9 | - [Ugly Number](./ugly-numbers2254.md)
10 | - [Greatest Common Divisor of Strings](./greatest-common-divisor-of-strings.md)
11 | - [Find the position of M-th item](./find-the-position-of-m-th-item1723.md)
12 | - [Total Decoding Messages](./total-decoding-messages1235.md)
13 | - [Number following a pattern](./number-following-a-pattern3126.md)
14 | - [Max 10 numbers in a list having 10M entries](./k-largest-elements3736.md)
15 | - [Find Missing And Repeating](./find-missing-and-repeating2512.md)
16 | - [Squares in N*N Chessboard](./squares-in-nn-chessboard1801.md)
17 | - [Decode the string](./goldman-sachs/decode-the-string2444.md)
18 | - [Minimum Size Subarray Sum](./minimum-size-subarray-sum.md)
19 | - [Array Pair Sum Divisibility Problem](./array-pair-sum-divisibility-problem3257.md)
--------------------------------------------------------------------------------
/goldman-sachs/array-pair-sum-divisibility-problem3257.md:
--------------------------------------------------------------------------------
1 | # Array Pair Sum Divisibility Problem
2 |
3 | [](https://practice.geeksforgeeks.org/problems/array-pair-sum-divisibility-problem3257/1#)
4 |
5 | Given an array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair is divisible by k.
6 |
7 | ### Sample Input
8 | ```
9 | 4 6
10 | 9 7 5 3
11 | ```
12 |
13 | ### Sample Output
14 | ```
15 | True
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution {
21 | public:
22 | bool canPair(vector nums, int k) {
23 |
24 | if(nums.size() % 2) return false;
25 |
26 | unordered_map rem;
27 |
28 | for(int n: nums) {
29 | int r = n%k;
30 |
31 | if(r && rem.count(k - r) && rem[k - r] > 0) {
32 | --rem[k - r];
33 | rem[0] += 2;
34 | }
35 | else {
36 | ++rem[r];
37 | }
38 | }
39 |
40 | return rem[0] == nums.size();
41 | }
42 | };
43 | ```
44 |
45 | ### Accepted
46 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=44e5a1b367208553109b112ee8da26e2&pid=704691&user=jhasuraj)
47 |
--------------------------------------------------------------------------------
/goldman-sachs/count-the-subarrays-having-product-less-than-k1708.md:
--------------------------------------------------------------------------------
1 | # Count the subarrays having product less than k
2 |
3 | [](https://practice.geeksforgeeks.org/problems/count-the-subarrays-having-product-less-than-k1708/1/)
4 |
5 | Given an array of positive numbers, the task is to find the number of possible contiguous subarrays having product less than a given number k.
6 |
7 | ### Sample Input
8 | ```
9 | 4 10
10 | 1 2 3 4
11 | ```
12 | ### Sample Output
13 | ```
14 | 7
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution{
20 | public:
21 | int countSubArrayProductLessThanK(const vector& a, int n, long long k) {
22 | int left = 0;
23 | int right = 0;
24 | long long prod = 1;
25 | int count = 0;
26 |
27 | for(int i = 0; i < n; ++i) {
28 | right = i;
29 |
30 | prod *= a[right];
31 | count += right - left + 1;
32 |
33 | while(prod >= k) {
34 | prod /= a[left++];
35 | count -= 1;
36 | }
37 | }
38 |
39 | return count;
40 | }
41 | };
42 | ```
43 |
44 | ### Accepted
45 |
46 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=5c7858d0d792b06c87077adf6e8d99d8&pid=703804&user=jhasuraj)
47 |
--------------------------------------------------------------------------------
/goldman-sachs/decode-the-string2444.md:
--------------------------------------------------------------------------------
1 | # Decode the string
2 |
3 | [](https://practice.geeksforgeeks.org/problems/decode-the-string2444/1#)
4 |
5 | An encoded string (s) is given, the task is to decode it. The pattern in which the strings were encoded were as follows
6 |
7 | **original string:** abbbababbbababbbab
8 |
9 | **encoded string:** 3[a3[b]1[ab]]
10 |
11 | ### Sample Input
12 | ```
13 | 3[b2[ca]]
14 | ```
15 | ### Sample Output
16 | ```
17 | bcacabcacabcaca
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | class Solution{
23 | public:
24 | string decodeRecursive(string &s, int left, int right) {
25 |
26 | int depth = 0, start, end, count = 1;
27 | string str = "", decoded = "";
28 | bool push = false, collecting_number = false;
29 |
30 | for(int i = left; i <= right; ++i) {
31 | char c = s[i];
32 |
33 | if(c == '[') {
34 | if(depth == 0) {
35 | start = i+1;
36 | }
37 | ++depth;
38 | }
39 | else if(c == ']') {
40 | --depth;
41 | if(depth == 0) {
42 | end = i-1;
43 | }
44 | }
45 |
46 | if(depth == 0) {
47 |
48 | if('0' <= c && c <= '9') {
49 | while(!collecting_number && count--) decoded += str;
50 | if(!collecting_number) count = 0;
51 | str = "";
52 | count = count * 10 + c - '0';
53 | collecting_number = true;
54 | }
55 | else {
56 | collecting_number = false;
57 | }
58 |
59 | if(c == ']') {
60 | str += decodeRecursive(s, start, end);
61 | while(!collecting_number && count--) decoded += str;
62 | count = 1;
63 | str = "";
64 | }
65 | else if('a' <= c && c <= 'z') {
66 | str += c;
67 | }
68 |
69 | }
70 | }
71 |
72 | while(count--) decoded += str;
73 |
74 | return decoded;
75 |
76 | }
77 | string decodedString(string s){
78 | return decodeRecursive(s, 0, s.size() - 1);
79 | }
80 | };
81 | ```
82 |
83 | ### Accepted
84 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=461e6f8673561496a9b93480ef7abdb8&pid=705287&user=jhasuraj)
85 |
--------------------------------------------------------------------------------
/goldman-sachs/find-missing-and-repeating2512.md:
--------------------------------------------------------------------------------
1 | # Find Missing And Repeating
2 |
3 | [](https://practice.geeksforgeeks.org/problems/find-missing-and-repeating2512/1/#)
4 |
5 | Given an unsorted array Arr of size N of positive integers. One number 'A' from set {1, 2, …N} is missing and one number 'B' occurs twice in array. Find these two numbers.
6 |
7 | ### Sample Input
8 | ```
9 | 2
10 | 2 2
11 | ```
12 | ### Sample Output
13 | ```
14 | 2 1
15 | ```
16 |
17 | ### Solution
18 | > Time: O(N), Space: O(N)
19 | ```cpp
20 | class Solution{
21 | public:
22 | int *findTwoElement(int *arr, int n) {
23 | vector nums(n+1, 0);
24 |
25 | int repeated;
26 |
27 | int ans[2];
28 |
29 | for(int i = 0; i < n; ++i) {
30 | int num = arr[i];
31 | if(nums[num]) {
32 | ans[0] = num;
33 | }
34 | nums[num] = nums[num] ^ 1;
35 | }
36 |
37 | for(int i = 1; i <= n; ++i) {
38 | if(nums[i] == 0 && i != ans[0]) {
39 | ans[1] = i;
40 | break;
41 | }
42 | }
43 |
44 | int *ptr;
45 | ptr = ans;
46 |
47 | return ptr;
48 |
49 | }
50 | };
51 | ```
52 |
53 | ### Accepted
54 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=5fc89ed14fb72d9cf92175879d66431b&pid=702678&user=jhasuraj)
55 |
--------------------------------------------------------------------------------
/goldman-sachs/find-the-position-of-m-th-item1723.md:
--------------------------------------------------------------------------------
1 | # Find the position of M-th item
2 |
3 | [](https://practice.geeksforgeeks.org/problems/find-the-position-of-m-th-item1723/1#)
4 |
5 | M items are to be delivered in a circle of size N. Find the position where the M-th item will be delivered if we start from a given position K. Note that items are distributed at adjacent positions starting from K.
6 |
7 | ### Sample Input
8 | ```
9 | 5 8 2
10 | ```
11 | ### Sample Output
12 | ```
13 | 4
14 | ```
15 |
16 | ### Solution
17 | ```cpp
18 | class Solution {
19 | public:
20 | int findPosition(int N , int M , int K) {
21 | if(N == 1) return 1;
22 |
23 | int pos = 1 + (M + K - 2) % N;
24 | return pos;
25 | }
26 | };
27 | ```
28 |
29 | ### Accepted
30 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=5caae207066adc0ddc8d191f13e6b1ce&pid=704216&user=jhasuraj)
31 |
--------------------------------------------------------------------------------
/goldman-sachs/greatest-common-divisor-of-strings.md:
--------------------------------------------------------------------------------
1 | # Greatest Common Divisor of Strings
2 |
3 | [](https://leetcode.com/problems/greatest-common-divisor-of-strings/)
4 |
5 | For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times).
6 |
7 | Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.
8 |
9 | ### Example 1
10 | ```
11 | Input: str1 = "ABCABC", str2 = "ABC"
12 | Output: "ABC"
13 | ```
14 | ### Example 2
15 | ```
16 | Input: str1 = "LEET", str2 = "CODE"
17 | Output: ""
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | class Solution {
23 | public:
24 | string gcdOfStrings(string str1, string str2) {
25 | string ans = "";
26 | string gcd = "";
27 |
28 | int i = 0;
29 | while(i < str1.size() && i < str2.size() && str1[i] == str2[i]) {
30 | gcd += str1[i];
31 | ++i;
32 | if(str1.size() % gcd.size() == 0 && str2.size() % gcd.size() == 0) {
33 | ans = gcd;
34 | }
35 | }
36 |
37 | int j = i;
38 | while(ans.size() && j < str1.size()) {
39 | if(str1[j] != ans[j % ans.size()]) {
40 | return "";
41 | }
42 | ++j;
43 | }
44 |
45 | int k = i;
46 | while(ans.size() && k < str2.size()) {
47 | if(str2[k] != ans[k % ans.size()]) {
48 | return "";
49 | }
50 | ++k;
51 | }
52 |
53 | return ans;
54 | }
55 | };
56 | ```
57 |
58 | ### Accepted
59 | [](https://leetcode.com/submissions/detail/611512412/)
60 |
--------------------------------------------------------------------------------
/goldman-sachs/k-largest-elements3736.md:
--------------------------------------------------------------------------------
1 | # Max 10 numbers in a list having 10M entries (K largest elements)
2 |
3 | [](https://practice.geeksforgeeks.org/problems/k-largest-elements3736/1)
4 |
5 | Given an array of N positive integers, print k largest elements from the array.
6 |
7 | ### Sample Input
8 | ```
9 | 5 2
10 | 12 5 787 1 23
11 | ```
12 | ### Sample Output
13 | ```
14 | 787 23
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution
20 | {
21 | public:
22 | vector kLargest(int arr[], int n, int k)
23 | {
24 | priority_queue, greater >pq;
25 |
26 | for(int i = 0; i < k; ++i) {
27 | pq.push(arr[i]);
28 | }
29 |
30 | for(int i = k; i < n; ++i) {
31 | if(pq.top() < arr[i]) {
32 | pq.pop();
33 | pq.push(arr[i]);
34 | }
35 | }
36 |
37 | vector ans;
38 | while (!pq.empty()) {
39 | ans.push_back(pq.top());
40 | pq.pop();
41 | }
42 |
43 | reverse(ans.begin(), ans.end());
44 |
45 | return ans;
46 | }
47 | };
48 | ```
49 |
50 | ### Accepted
51 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=40ca7928d3a443a6779ea07f3e96a8ff&pid=701352&user=jhasuraj)
52 |
--------------------------------------------------------------------------------
/goldman-sachs/minimum-size-subarray-sum.md:
--------------------------------------------------------------------------------
1 | # Minimum Size Subarray Sum
2 |
3 | [](https://leetcode.com/problems/minimum-size-subarray-sum)
4 |
5 | Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.
6 |
7 | ### Example 1
8 | ```
9 | Input: target = 7, nums = [2,3,1,2,4,3]
10 | Output: 2
11 | ```
12 |
13 | ### Example 2
14 | ```
15 | Input: target = 4, nums = [1,4,4]
16 | Output: 1
17 | ```
18 |
19 | ### Solution
20 | ```cpp
21 | class Solution {
22 | public:
23 | int minSubArrayLen(int target, vector& nums) {
24 | long long sum = 0;
25 | int left = 0, right = 0;
26 | int min_size = INT_MAX;
27 |
28 | for(int n: nums) {
29 |
30 | sum += n;
31 |
32 | while (sum >= target) {
33 | min_size = min(min_size, right - left + 1);
34 | sum -= nums[left++];
35 | }
36 |
37 | ++right;
38 | }
39 |
40 | return min_size == INT_MAX ? 0 : min_size;
41 | }
42 | };
43 | ```
44 |
45 | ### Accepted
46 | [](https://leetcode.com/submissions/detail/611916014/)
47 |
--------------------------------------------------------------------------------
/goldman-sachs/number-following-a-pattern3126.md:
--------------------------------------------------------------------------------
1 | # Number following a pattern
2 |
3 | [](https://practice.geeksforgeeks.org/problems/number-following-a-pattern3126/1#)
4 |
5 | Given a pattern containing only I's and D's. I for increasing and D for decreasing.
6 |
7 | Devise an algorithm to print the minimum number following that pattern.
8 |
9 | Digits from 1-9 and digits can't repeat.
10 |
11 | ### Sample Input
12 | ```
13 | D
14 | ```
15 | ### Sample Output
16 | ```
17 | 21
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | class Solution{
23 | public:
24 | string printMinNumberForPattern(string S){
25 |
26 | vectornum(S.size() + 1, 0);
27 | num[0] = 1;
28 |
29 | int max_int = 1;
30 |
31 | for(int i = 0; i < S.size(); ++i) {
32 | if(S[i] == 'I') {
33 | ++max_int;
34 | num[i + 1] = max_int;
35 | }
36 |
37 | int r = 0;
38 | while(i - r >= 0 && S[i - r] == 'D') {
39 | num[i - r + 1] = num[i - r];
40 | ++num[i - r];
41 | max_int = max(max_int, num[i - r]);
42 | ++r;
43 | }
44 | }
45 |
46 | for(auto n : num) {
47 | cout << n;
48 | }
49 |
50 | return "";
51 | }
52 | };
53 | ```
54 |
55 | ### Accepted
56 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=beb86d3e6d93f9ab3a81610235da44f9&pid=703607&user=jhasuraj)
57 |
--------------------------------------------------------------------------------
/goldman-sachs/overlapping-rectangles1924.md:
--------------------------------------------------------------------------------
1 | # Overlapping Rectangles
2 |
3 | [](https://practice.geeksforgeeks.org/problems/overlapping-rectangles1924/1/)
4 |
5 | Given two rectangles, find if the given two rectangles overlap or not. A rectangle is denoted by providing the x and y coordinates of two points: the left top corner and the right bottom corner of the rectangle. Two rectangles sharing a side are considered overlapping. (L1 and R1 are the extreme points of the first rectangle and L2 and R2 are the extreme points of the second rectangle).
6 |
7 | **Note:** It may be assumed that the rectangles are parallel to the coordinate axis.
8 | 
9 |
10 | ### Sample Input
11 | ```
12 | 0 10 10 0 5 5 15 0
13 | ```
14 | ### Sample Output
15 | ```
16 | 1
17 | ```
18 |
19 | ### Solution
20 | ```cpp
21 | class Solution {
22 | public:
23 | int doOverlap(int L1[], int R1[], int L2[], int R2[]) {
24 |
25 | if(
26 | L2[0] - R1[0] > 0 ||
27 | R1[1] - L2[1] > 0 ||
28 | L1[0] - R2[0] > 0 ||
29 | R2[1] - L1[1] > 0
30 | ) {
31 | return 0;
32 | }
33 | else {
34 | return 1;
35 | }
36 | }
37 | };
38 | ```
39 |
40 | ### Accepted
41 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=86b4ef19ca53a2d09b332f260a8acc8c&pid=705474&user=jhasuraj)
42 |
43 |
--------------------------------------------------------------------------------
/goldman-sachs/print-anagrams-together.md:
--------------------------------------------------------------------------------
1 | # Print Anagrams Together
2 |
3 | [](https://practice.geeksforgeeks.org/problems/print-anagrams-together/1/#)
4 |
5 | Given an array of strings, return all groups of strings that are anagrams. The groups must be created in order of their appearance in the original array. Look at the sample case for clarification.
6 |
7 | ### Sample Input
8 | ```
9 | 5
10 | act god cat dog tac
11 | ```
12 | ### Sample Output
13 | ```
14 | act cat tac
15 | god dog
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution{
21 | public:
22 | vector > Anagrams(vector& string_list) {
23 |
24 | unordered_map> ans_map;
25 |
26 | for(string &s: string_list) {
27 | string copy = s;
28 | sort(copy.begin(), copy.end());
29 | ans_map[copy].push_back(s);
30 | }
31 |
32 | vector< vector > ans;
33 |
34 | for(auto v: ans_map) {
35 | ans.push_back(v.second);
36 | }
37 |
38 | return ans;
39 | }
40 | };
41 | ```
42 |
43 | ### Accepted
44 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=6f74ea054ab4a7ac183196a83fd4b454&pid=701966&user=jhasuraj)
45 |
--------------------------------------------------------------------------------
/goldman-sachs/run-length-encoding.md:
--------------------------------------------------------------------------------
1 | # Run Length Encoding
2 |
3 | [](https://practice.geeksforgeeks.org/problems/run-length-encoding/1/)
4 |
5 | Given a string, Your task is to complete the function `encode` that returns the run length encoded string for the given string.
6 | eg if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6″.
7 | You are required to complete the function `encode` that takes only one argument the string which is to be encoded and returns the encoded string.
8 |
9 |
10 | ### Sample Input
11 | ```
12 | aaaabbbccc
13 | ```
14 | ### Sample Output
15 | ```
16 | a4b3c3
17 | ```
18 |
19 | ### Solution
20 | ```cpp
21 | string encode(string src)
22 | {
23 | char last = '-';
24 | string ans = "";
25 | int count = 0;
26 |
27 | for(char c: src) {
28 | if(c != last) {
29 | if(count) {
30 | ans += to_string(count);
31 | }
32 | ans += c;
33 | count = 1;
34 | }
35 | else {
36 | ++count;
37 | }
38 | last = c;
39 | }
40 | ans += to_string(count);
41 |
42 | return ans;
43 | }
44 | ```
45 |
46 | ### Accepted
47 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=40cf8cfde94db6354f0182a6793bcadf&pid=700243&user=jhasuraj)
48 |
49 |
--------------------------------------------------------------------------------
/goldman-sachs/squares-in-nn-chessboard1801.md:
--------------------------------------------------------------------------------
1 | # Squares in N*N Chessboard
2 |
3 | [](https://practice.geeksforgeeks.org/problems/squares-in-nn-chessboard1801/1#)
4 |
5 | Find total number of Squares in a N*N chessboard.
6 |
7 | ### Calculation
8 | 
9 |
10 |
11 | ### Sample Input
12 | ```
13 | 2
14 | ```
15 | ### Sample Output
16 | ```
17 | 5
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | class Solution {
23 | public:
24 | long long squaresInChessBoard(long long N) {
25 |
26 | long long ans = N * (N + 1) * (2*N + 1) / 6;
27 |
28 | return ans;
29 | }
30 | };
31 | ```
32 |
33 | ### Accepted
34 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=fa05c17a6461f5dbc7ff804201c6020d&pid=704775&user=jhasuraj)
35 |
--------------------------------------------------------------------------------
/goldman-sachs/total-decoding-messages1235.md:
--------------------------------------------------------------------------------
1 | # Total Decoding Messages
2 |
3 | [](https://practice.geeksforgeeks.org/problems/total-decoding-messages1235/1/#)
4 |
5 | A top secret message containing letters from A-Z is being encoded to numbers using the following mapping:
6 | ```
7 | 'A' -> 1
8 | 'B' -> 2
9 | .
10 | .
11 | 'Z' -> 26
12 | ```
13 | You are an FBI agent. You have to determine the total number of ways that message can be decoded, as the answer can be large return the answer modulo 109 + 7.
14 |
15 | **Note:** An empty digit sequence is considered to have one decoding. It may be assumed that the input contains valid digits from 0 to 9 and If there are leading 0’s, extra trailing 0’s and two or more consecutive 0’s then it is an invalid string.
16 |
17 | ### Sample Input
18 | ```
19 | 123
20 | ```
21 | ### Sample Output
22 | ```
23 | 3
24 | ```
25 |
26 | ### Solution
27 | ```cpp
28 | class Solution {
29 | public:
30 | map cache;
31 | int mod = 1e9+7;
32 | int CountWays(string str, int n = 0){
33 |
34 | if(str[0] == '0') return 0;
35 |
36 | int end = str.size() - n - 1;
37 |
38 | if(end < 1) return 1;
39 |
40 | if(cache.count(end)) return cache[end];
41 |
42 | int count = 0;
43 | if(str[end] != '0') {
44 | count = CountWays(str, n + 1);
45 | }
46 |
47 | if(str[end-1] == '1' || (str[end-1] == '2' && str[end] <= '6')) {
48 | count += CountWays(str, n + 2);
49 | }
50 |
51 | cache[end] = count % mod;
52 |
53 | return count % mod;
54 | }
55 |
56 | };
57 | ```
58 |
59 | ### Accepted
60 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=6849c8e3a93717352c31f0134df5a6dd&pid=705327&user=jhasuraj)
61 |
--------------------------------------------------------------------------------
/goldman-sachs/ugly-numbers2254.md:
--------------------------------------------------------------------------------
1 | # Ugly Numbers
2 |
3 | [](https://practice.geeksforgeeks.org/problems/ugly-numbers2254/1/)
4 |
5 | Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, 1 is included. Write a program to find Nth Ugly Number.
6 |
7 | ### Sample Input
8 | ```
9 | 10
10 | ```
11 | ### Sample Output
12 | ```
13 | 12
14 | ```
15 |
16 | ### Solution
17 | ```cpp
18 | class Solution{
19 | public:
20 | // #define ull unsigned long long
21 | /* Function to get the nth ugly number*/
22 | ull getNthUglyNo(int n) {
23 | vector ugly_nums(n + 1);
24 | ugly_nums[1] = 1;
25 | int p2 = 1, p3 = 1, p5 = 1;
26 |
27 | for(int i = 2; i <= n; ++i) {
28 | ugly_nums[i] = min({ 2ll * ugly_nums[p2], 3ll * ugly_nums[p3], 5ll * ugly_nums[p5] });
29 | if(ugly_nums[i] == 2ll * ugly_nums[p2]) ++p2;
30 | if(ugly_nums[i] == 3ll * ugly_nums[p3]) ++p3;
31 | if(ugly_nums[i] == 5ll * ugly_nums[p5]) ++p5;
32 | }
33 |
34 | return ugly_nums.back();
35 | }
36 | };
37 | ```
38 |
39 | ### Accepted
40 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=2eb0648341e23e7fd4f1cfeb64421cde&pid=703093&user=jhasuraj)
41 |
--------------------------------------------------------------------------------
/intuit/as-far-from-land-as-possible.md:
--------------------------------------------------------------------------------
1 | # As Far from Land as Possible
2 |
3 | [](https://leetcode.com/problems/as-far-from-land-as-possible/)
4 |
5 | Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.
6 |
7 | The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
8 |
9 | ### Example 1
10 | ```
11 | Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
12 | Output: 2
13 | ```
14 |
15 | ### Example 2
16 | ```
17 | Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
18 | Output: 4
19 | ```
20 |
21 | ### Solution
22 | ```cpp
23 | class Solution {
24 | public:
25 | void bfs(int ROW, int COL, queue> &line, vector>& distance) {
26 | while(!line.empty()) {
27 | vector current_cell = line.front(); line.pop();
28 | int row = current_cell[0];
29 | int col = current_cell[1];
30 | int dis = current_cell[2];
31 |
32 | dis = distance[row][col] = min(dis, distance[row][col]);
33 |
34 | //top
35 | if(row > 0 && (dis + 1) < distance[row - 1][ col]) {
36 | line.push({row - 1, col, dis + 1});
37 | }
38 |
39 | //right
40 | if(col < (COL - 1 )&& (dis + 1) < distance[row][col + 1]) {
41 | line.push({row, col + 1, dis + 1});
42 | }
43 |
44 | //bottom
45 | if(row < (ROW - 1) && (dis + 1) < distance[row + 1][col]) {
46 | line.push({row + 1, col, dis + 1});
47 | }
48 |
49 | //left
50 | if(col > 0 && (dis + 1) < distance[row][col - 1]) {
51 | line.push({row, col - 1, dis + 1});
52 | }
53 | }
54 | }
55 |
56 | int maxDistance(vector>& grid) {
57 | int ROW = grid.size();
58 | int COL = grid[0].size();
59 |
60 | vector> distance(ROW, vector(COL, INT_MAX));
61 | queue> line;
62 |
63 | int ans = 0;
64 | for(int i = 0; i < ROW; ++i) {
65 | for(int j = 0; j < COL; ++j) {
66 | if(grid[i][j]) {
67 | line.push({i, j, 0});
68 | };
69 | }
70 | }
71 |
72 | bfs(ROW, COL, line, distance);
73 |
74 | for(int i = 0; i < ROW; ++i) {
75 | for(int j = 0; j < COL; ++j) {
76 | ans = max(ans, distance[i][j]);
77 | }
78 | }
79 |
80 | return (ans == 0 || ans == INT_MAX ? -1 : ans);
81 | }
82 | };
83 | ```
84 |
85 | ### Accepted
86 | [](https://leetcode.com/submissions/detail/629321714/)
87 |
--------------------------------------------------------------------------------
/intuit/capacity-to-ship-packages-within-d-days.md:
--------------------------------------------------------------------------------
1 | # Capacity To Ship Packages Within D Days
2 |
3 | [](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/)
4 |
5 | A conveyor belt has packages that must be shipped from one port to another within days days.
6 |
7 | The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.
8 |
9 | Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.
10 |
11 | ### Example 1
12 | ```
13 | Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
14 | Output: 15
15 | ```
16 |
17 | ### Example 2
18 | ```
19 | Input: weights = [3,2,2,4,1,4], days = 3
20 | Output: 6
21 | ```
22 |
23 | ### Solution
24 | ```cpp
25 | class Solution {
26 | public:
27 | int minLargestSum(vector& array, int m, int start, int end, vector& presum, vector>& cache) {
28 | if(m == 1) {
29 | return presum[end] - presum[start];
30 | }
31 | if(cache[start][m] != -1) return cache[start][m];
32 |
33 | int ans = INT_MAX;
34 |
35 | for(int i = start + 1; i <= end - m + 1; ++i) {
36 | int largest_sum = max(
37 | presum[i] - presum[start],
38 | minLargestSum(array, m - 1, i, end, presum, cache)
39 | );
40 | ans = min(ans, largest_sum);
41 | }
42 |
43 | return cache[start][m] = ans;
44 | }
45 |
46 | int shipWithinDays(vector& weights, int days) {
47 | vector presum(weights.size() + 1, 0);
48 | vector> cache(weights.size(), vector(days+1, -1));
49 |
50 | for(int i = 0; i < weights.size(); ++i) {
51 | presum[i + 1] = presum[i] + weights[i];
52 | }
53 |
54 | return minLargestSum(weights, days, 0, weights.size(), presum, cache);
55 | }
56 | };
57 | ```
58 |
59 | ### Accepted
60 | [](https://leetcode.com/submissions/detail/627778447/)
--------------------------------------------------------------------------------
/intuit/construct-quad-tree.md:
--------------------------------------------------------------------------------
1 | # Construct Quad Tree
2 |
3 | [](https://leetcode.com/problems/construct-quad-tree/)
4 |
5 | Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree.
6 |
7 | Return the root of the Quad-Tree representing the grid.
8 |
9 | Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.
10 |
11 | ### Example 1
12 | ```
13 | Input: grid = [[0,1],[1,0]]
14 | Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution {
20 | public:
21 | int sum(int r1, int c1, int r2, int c2, vector> &presum) {
22 | return presum[r2+1][c2+1] - presum[r1][c2+1] - presum[r2+1][c1] + presum[r1][c1];
23 | }
24 |
25 | int val(int r1, int c1, int r2, int c2, vector> &presum) {
26 | int total = sum(r1, c1, r2, c2, presum);
27 | int area = (r2 - r1 + 1)*(c2 - c1 + 1);
28 |
29 | if(total == 0) return 0;
30 | if(total == area) return 1;
31 | return -1;
32 | }
33 |
34 | Node* construct(int r1, int c1, int r2, int c2, vector> &presum) {
35 | int value = val(r1, c1, r2, c2, presum);
36 |
37 | if(value != -1) {
38 | return new Node(value, true);
39 | }
40 |
41 | int side = (r2 - r1 + 1) / 2;
42 |
43 | return new Node(false, false,
44 | construct(r1, c1, r2 - side, c2 - side, presum), // topLeft
45 | construct(r1, c1 + side, r2 - side, c2, presum), // topRight
46 | construct(r1 + side, c1, r2, c2 - side, presum), // bottomLeft
47 | construct(r1 + side, c1 + side, r2, c2, presum) // bottomRight
48 | );
49 | }
50 |
51 | Node* construct(vector>& grid) {
52 | int side = grid.size();
53 |
54 | vector> presum(side + 1, vector(side + 1, 0));
55 |
56 | for(int r = 0; r < side; ++r) {
57 | for(int c = 0; c < side; ++c) {
58 | presum[r + 1][c + 1] = grid[r][c] + presum[r][c + 1] + presum[r + 1][c] - presum[r][c];
59 | }
60 | }
61 |
62 | return construct(0, 0, side - 1, side - 1, presum);
63 | }
64 | };
65 | ```
66 |
67 | ### Accepted
68 | [](https://leetcode.com/submissions/detail/628251995/)
--------------------------------------------------------------------------------
/intuit/course-schedule-ii.md:
--------------------------------------------------------------------------------
1 | # Course Schedule II
2 |
3 | [](https://leetcode.com/problems/course-schedule-ii/)
4 |
5 | There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
6 |
7 | - For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
8 |
9 | Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
10 |
11 | ### Example 1
12 | ```
13 | Input: numCourses = 2, prerequisites = [[1,0]]
14 | Output: [0,1]
15 | ```
16 |
17 | ### Example 2
18 | ```
19 | Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
20 | Output: [0,2,1,3]
21 | ```
22 |
23 | ### Solution
24 | ```cpp
25 | class Solution {
26 | public:
27 | bool topologicalSort(int course, vector> &courses, vector &state, vector &ans) {
28 | if(state[course] == 2) return true;
29 | if(state[course] == 1) return false;
30 |
31 | state[course] = 1; // visited
32 |
33 | for(auto prerequisites: courses[course]) {
34 | if(!topologicalSort(prerequisites, courses, state, ans)) {
35 | return false;
36 | }
37 | }
38 |
39 | ans.push_back(course);
40 |
41 | state[course] = 2; // completed
42 |
43 | return true;
44 | }
45 |
46 | vector findOrder(int numCourses, vector>& prerequisites) {
47 | vector> courses(numCourses);
48 | vector state(numCourses, 0);
49 |
50 | for(auto course: prerequisites) {
51 | courses[course[0]].push_back(course[1]);
52 | }
53 |
54 | vector ans;
55 |
56 | for(int i = 0; i < numCourses; ++i) {
57 | if(state[i]) continue;
58 | if(!topologicalSort(i, courses, state, ans)) {
59 | return vector(0);
60 | }
61 | }
62 |
63 | return ans;
64 | }
65 | };
66 | ```
67 |
68 | ### Accepted
69 | [](https://leetcode.com/submissions/detail/628341320/)
70 |
--------------------------------------------------------------------------------
/intuit/find-in-mountain-array.md:
--------------------------------------------------------------------------------
1 | # Find in Mountain Array
2 |
3 | [](https://leetcode.com/problems/find-in-mountain-array/)
4 |
5 | Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.
6 |
7 | ### Example 1
8 | ```
9 | Input: array = [1,2,3,4,5,3,1], target = 3
10 | Output: 2
11 | ```
12 |
13 | ### Example 2
14 | ```
15 | Input: array = [0,1,2,4,2,1], target = 3
16 | Output: -1
17 | ```
18 |
19 | ### Solution
20 | ```cpp
21 | /**
22 | * // This is the MountainArray's API interface.
23 | * // You should not implement it, or speculate about its implementation
24 | * class MountainArray {
25 | * public:
26 | * int get(int index);
27 | * int length();
28 | * };
29 | */
30 |
31 | class Solution {
32 | public:
33 | int binarySearch(int target, MountainArray &mountainArr, int left, int right, bool asc) {
34 | while(left <= right) {
35 | int mid = (left + right)/2;
36 |
37 | int val = mountainArr.get(mid);
38 |
39 | if(val == target) {
40 | return mid;
41 | }
42 | if(asc) {
43 | if(val > target) {
44 | right = mid - 1;
45 | }
46 | else {
47 | left = mid + 1;
48 | }
49 | }
50 | else {
51 | if(val > target) {
52 | left = mid + 1;
53 | }
54 | else {
55 | right = mid - 1;
56 | }
57 | }
58 | }
59 | return -1;
60 | }
61 | int findInMountainArray(int target, MountainArray &mountainArr) {
62 | int length = mountainArr.length();
63 |
64 | int left = 0, right = length - 1, mid, peek;
65 |
66 | while(left < right) {
67 | mid = (left + right)/2;
68 |
69 | int a = mountainArr.get(mid);
70 | int b = mountainArr.get(mid + 1);
71 |
72 | if(a > b) {
73 | right = mid;
74 | peek = mid;
75 | }
76 | else {
77 | left = mid + 1;
78 | peek = mid + 1;
79 | }
80 | }
81 |
82 | int leftSearch = binarySearch(target, mountainArr, 0, peek, true);
83 | if(leftSearch >= 0) return leftSearch;
84 |
85 | int rightSearch = binarySearch(target, mountainArr, peek, length - 1, false);
86 | return rightSearch;
87 | }
88 | };
89 | ```
90 |
91 | ### Accepted
92 | [](https://leetcode.com/submissions/detail/627700749/)
93 |
--------------------------------------------------------------------------------
/intuit/koko-eating-bananas.md:
--------------------------------------------------------------------------------
1 | # Koko Eating Bananas
2 |
3 | [](https://leetcode.com/problems/koko-eating-bananas/)
4 |
5 | Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.
6 |
7 | Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.
8 |
9 | Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
10 |
11 | Return the minimum integer k such that she can eat all the bananas within h hours.
12 |
13 | ### Example 1
14 | ```
15 | Input: piles = [3,6,7,11], h = 8
16 | Output: 4
17 | ```
18 |
19 | ### Example 2
20 | ```
21 | Input: piles = [30,11,23,4,20], h = 5
22 | Output: 30
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 | int minEatingSpeed(vector& piles, int H) {
30 | int low = 1;
31 | int high = *max_element(piles.begin(), piles.end());
32 | int ans = high;
33 |
34 | while(low < high) {
35 | int mid = (low + high) >> 1;
36 |
37 | int h = 0;
38 | for(int bananas: piles) {
39 | h += ceil((double) bananas/mid);
40 | }
41 |
42 | if(h == H) {
43 | ans = min(ans, mid);
44 | }
45 |
46 | if(h > H) {
47 | low = mid + 1;
48 | }
49 | else {
50 | high = mid;
51 | }
52 | }
53 |
54 | return ans;
55 | }
56 | };
57 | ```
58 |
59 | ### Accepted
60 | [](https://leetcode.com/submissions/detail/629360419/)
--------------------------------------------------------------------------------
/intuit/largest-number-in-k-swaps.md:
--------------------------------------------------------------------------------
1 | # Largest number in K swaps
2 |
3 | [](https://practice.geeksforgeeks.org/problems/largest-number-in-k-swaps-1587115620/1#)
4 |
5 | Given a number K and string str of digits denoting a positive integer, build the largest number possible by performing swap operations on the digits of str at most K times.
6 |
7 | ### Sample Input
8 | ```
9 | 1
10 | 3
11 | 6278134320804246
12 | ```
13 |
14 | ### Sample Output
15 | ```
16 | 8876634320204241
17 | ```
18 |
19 | ### Solution
20 | ```cpp
21 | class Solution {
22 | public:
23 | void swap(char &a, char &b) {
24 | a = a ^ b;
25 | b = a ^ b;
26 | a = a ^ b;
27 | }
28 |
29 | string findMaximumNum(string &str, int k, int index = 0)
30 | {
31 | int length = str.length();
32 |
33 | if(k == 0 || index >= length) {
34 | return str;
35 | }
36 |
37 | int max_index = index;
38 | vector max_indices;
39 |
40 | for(int i = index + 1; i < length; ++i) {
41 | if(str[max_index] <= str[i]) {
42 | if(str[max_index] < str[i]) {
43 | max_indices.clear();
44 | }
45 | max_index = i;
46 | max_indices.push_back(i);
47 | }
48 | }
49 |
50 | if(str[max_index] == str[index]) {
51 | return findMaximumNum(str, k, index + 1);
52 | }
53 |
54 | string ans = str;
55 |
56 | for(int max_index: max_indices) {
57 | swap(str[max_index], str[index]);
58 | ans = max(ans, findMaximumNum(str, k - 1, index + 1));
59 | swap(str[max_index], str[index]);
60 | }
61 |
62 | return ans;
63 | }
64 | };
65 | ```
66 |
67 | ### Accepted
68 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=a2ac5f73bc57db27668984a121f07139&pid=701369&user=jhasuraj)
--------------------------------------------------------------------------------
/intuit/min-swaps-to-arrange-binary-grid.md:
--------------------------------------------------------------------------------
1 | # Minimum Swaps to Arrange a Binary Grid
2 |
3 | [](https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/)
4 |
5 | Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
6 |
7 | A grid is said to be valid if all the cells above the main diagonal are zeros.
8 |
9 | Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
10 |
11 | The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).
12 |
13 | ### Example 1
14 | ```
15 | Input: grid = [[0,0,1],[1,1,0],[1,0,0]]
16 | Output: 3
17 | ```
18 |
19 | ### Example 2
20 | ```
21 | Input: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]
22 | Output: -1
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 | int minSwaps(vector>& grid) {
30 |
31 | int side = grid.size();
32 |
33 | vector suffix0(side);
34 |
35 | for(int i = 0; i < side; ++i) {
36 | int count = 0;
37 | while(count < side && grid[i][side - count - 1] == 0) ++count;
38 | suffix0[i] = count;
39 | }
40 |
41 | int count = 0;
42 |
43 | for(int i = 0; i < side; ++i) {
44 | int j = i;
45 |
46 | while(j < side && suffix0[j] < side - 1 - i) ++j;
47 |
48 | if(j == side) {
49 | return -1;
50 | }
51 |
52 | for(; j > i; --j) {
53 | swap(suffix0[j], suffix0[j - 1]);
54 | count++;
55 | }
56 | }
57 |
58 | return count;
59 | }
60 | };
61 | ```
62 |
63 | ### Accepted
64 | [](https://leetcode.com/submissions/detail/629008220/)
--------------------------------------------------------------------------------
/intuit/minimum-sum-partition.md:
--------------------------------------------------------------------------------
1 | # Minimum sum partition
2 |
3 | [](https://practice.geeksforgeeks.org/problems/minimum-sum-partition3317/1/#)
4 |
5 | Given an integer array arr of size N, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum and find the minimum difference
6 |
7 | ### DP Table
8 | 
9 |
10 | ### Sample Input
11 | ```
12 | 8
13 | 5 6 6 5 7 4 7 6
14 | ```
15 | ### Sample Output
16 | ```
17 | 0
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | class Solution {
23 |
24 | public:
25 | int minDifference(int arr[], int n) {
26 |
27 | sort(arr, arr+n);
28 |
29 | int sum = accumulate(arr, arr + n, 0);
30 |
31 | int half = sum/2;
32 |
33 | vector< vector > dp(n + 1, vector(half + 1, 0));
34 |
35 | for(int i = 0; i < n; ++i) {
36 | for(int j = 1; j <= half; ++j) {
37 | if(j < arr[i]) {
38 | dp[i+1][j] = dp[i][j];
39 | continue;
40 | }
41 | dp[i+1][j] = max({arr[i], dp[i][j - arr[i]] + arr[i], dp[i][j]});
42 | }
43 | }
44 | return sum - dp.back().back()*2;
45 | }
46 | };
47 | ```
48 |
49 | ### Accepted
50 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=3f5cb6117c6bbc13d452b2aef30dcc85&pid=704140&user=jhasuraj)
51 |
--------------------------------------------------------------------------------
/intuit/missing-no-in-string.md:
--------------------------------------------------------------------------------
1 | # Find the missing no in string
2 |
3 | [](https://practice.geeksforgeeks.org/problems/find-the-missing-no-in-string/1/#)
4 |
5 | Given a string consisting of some numbers, not separated by any separator. The numbers are positive integers and the sequence increases by one at each number except the missing number. The task is to complete the function missingNumber which return's the missing number. The numbers will have no more than six digits. Print -1 if input sequence is not valid.
6 |
7 | **Note:** Its is guaranteed that if the string is valid, then it is sure that atleast one number would be missing from the string.
8 |
9 | ### Sample Input
10 | ```
11 | 1
12 | 1234567810111213141516
13 | ```
14 |
15 | ### Sample Output
16 | ```
17 | 9
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | int missingNumber(const string& str)
23 | {
24 | int len = str.size();
25 | int max_window = min(6, len/2);
26 |
27 | for(int w = 1; w <= max_window; ++w) {
28 | int last_num = 0, num = 0;
29 | bool searching = true, solved = false;
30 | int missing_number;
31 |
32 | for(int i = 0; i < w; ++i) {
33 | last_num = last_num * 10 + str[i] - '0';
34 | }
35 |
36 | int window_size = (int) log10(last_num + 1) + 1;
37 |
38 | for(int d = w; d < len; d += window_size) {
39 | window_size = (int) log10(last_num + 1) + 1;
40 | num = 0;
41 | for(int i = 0; i < window_size; ++i) {
42 | num = num * 10 + str[d + i] - '0';
43 | }
44 |
45 | if(num != last_num + 1 && (int)log10(last_num + 1) < (int)log10(last_num + 2)) {
46 | num = 0;
47 | window_size = (int) log10(last_num + 2) + 1;
48 | for(int i = 0; i < window_size; ++i) {
49 | num = num * 10 + str[d + i] - '0';
50 | }
51 | }
52 |
53 | if(num == last_num + 2) {
54 | if(searching) {
55 | searching = false;
56 | solved = true;
57 | missing_number = last_num + 1;
58 | }
59 | else {
60 | solved = false;
61 | break;
62 | }
63 | }
64 | else if(num != last_num + 1) {
65 | solved = false;
66 | break;
67 | }
68 | last_num = num;
69 | }
70 |
71 | if(solved) {
72 | return missing_number;
73 | }
74 | }
75 |
76 | return -1;
77 | }
78 | ```
79 |
80 | ### Accepted
81 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=fe529bd2a37e75bfc3f73473c37b2595&pid=700489&user=jhasuraj)
82 |
--------------------------------------------------------------------------------
/intuit/number-of-boomerangs.md:
--------------------------------------------------------------------------------
1 | # Number of Boomerangs
2 |
3 | [](https://leetcode.com/problems/number-of-boomerangs/)
4 |
5 | You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
6 |
7 | Return the number of boomerangs.
8 |
9 | ### Example 1
10 | ```
11 | Input: points = [[0,0],[1,0],[2,0]]
12 | Output: 2
13 | ```
14 |
15 | ### Example 2
16 | ```
17 | Input: points = [[1,1],[2,2],[3,3]]
18 | Output: 2
19 | ```
20 |
21 | ### Solution
22 | ```cpp
23 | class Solution {
24 | public:
25 | int squaredDistance(vector &a, vector &b) {
26 | return (a[0] - b[0])*(a[0] - b[0]) + (a[1] - b[1])*(a[1] - b[1]);
27 | }
28 |
29 | int numberOfBoomerangs(vector>& points) {
30 | int len = points.size();
31 |
32 | vector> dist(len);
33 |
34 | for(int i = 0; i < len; ++i) {
35 | for(int j = i + 1; j < len; ++j) {
36 | int distance = squaredDistance(points[i], points[j]);
37 | ++dist[i][distance];
38 | ++dist[j][distance];
39 | }
40 | }
41 |
42 | int ans = 0;
43 |
44 | for(auto point: dist) {
45 | for(auto d: point) {
46 | ans += d.second * (d.second - 1);
47 | }
48 | }
49 |
50 | return ans;
51 | }
52 | };
53 | ```
54 |
55 | ### Accepted
56 | [](https://leetcode.com/submissions/detail/628125746/)
57 |
--------------------------------------------------------------------------------
/intuit/number-of-provinces.md:
--------------------------------------------------------------------------------
1 | # Number of Provinces
2 |
3 | [](https://leetcode.com/problems/number-of-provinces/)
4 |
5 | There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
6 |
7 | A province is a group of directly or indirectly connected cities and no other cities outside of the group.
8 |
9 | You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.
10 |
11 | Return the total number of provinces.
12 |
13 | ### Example 1
14 | ```
15 | Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
16 | Output: 2
17 | ```
18 |
19 | ### Example 2
20 | ```
21 | Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
22 | Output: 3
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 | int findCircleNum(vector>& isConnected) {
30 | int N = isConnected.size();
31 |
32 | vector visited(N, false);
33 |
34 | queue line;
35 |
36 | int province = 0;
37 |
38 | for(int r = 0; r < N; ++r) {
39 | if(visited[r]) continue;
40 |
41 | line.push(r);
42 | visited[r] = true;
43 |
44 | while(!line.empty()) {
45 | int current = line.front(); line.pop();
46 | for(int c = 0; c < N; ++c) {
47 | if(isConnected[c][current] && !visited[c]) {
48 | line.push(c);
49 | visited[c] = true;
50 | }
51 | }
52 | }
53 |
54 | ++province;
55 | }
56 |
57 | return province;
58 | }
59 | };
60 | ```
61 |
62 | ### Accepted
63 | [](https://leetcode.com/submissions/detail/628166090/)
64 |
--------------------------------------------------------------------------------
/intuit/pacific-atlantic-water-flow.md:
--------------------------------------------------------------------------------
1 | # Pacific Atlantic Water Flow
2 |
3 | [](https://leetcode.com/problems/pacific-atlantic-water-flow/)
4 |
5 | There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
6 |
7 | The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).
8 |
9 | The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
10 |
11 | Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.
12 |
13 | ### Example 1
14 | ```
15 | Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
16 | Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
17 | ```
18 |
19 | ### Example 2
20 | ```
21 | Input: heights = [[2,1],[1,2]]
22 | Output: [[0,0],[0,1],[1,0],[1,1]]
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 |
30 | void pacificBFS(int row, int col, vector>& heights, vector>& visited) {
31 |
32 | int m = heights.size();
33 | int n = heights[0].size();
34 |
35 | if(visited[row][col] == 1) {
36 | return;
37 | }
38 |
39 | queue> pq;
40 |
41 | pq.push({row, col});
42 | visited[row][col] = 1;
43 |
44 | while(!pq.empty()) {
45 |
46 | pair current = pq.front(); pq.pop();
47 |
48 | int row = current.first;
49 | int col = current.second;
50 | int height = heights[row][col];
51 |
52 | // top
53 | if(row > 0 && visited[row - 1][col] != 1 && heights[row - 1][col] >= height) {
54 | pq.push({row - 1, col});
55 | visited[row - 1][col] = 1;
56 | }
57 |
58 | // left
59 | if(col > 0 && visited[row][col - 1] != 1 && heights[row][col - 1] >= height) {
60 | pq.push({row, col - 1});
61 | visited[row][col - 1] = 1;
62 | }
63 |
64 | // right
65 | if(col < n - 1 && visited[row][col + 1] != 1 && heights[row][col + 1] >= height) {
66 | pq.push({row, col + 1});
67 | visited[row][col + 1] = 1;
68 | }
69 |
70 | // bottom
71 | if(row < m - 1 && visited[row + 1][col] != 1 && heights[row + 1][col] >= height) {
72 | pq.push({row + 1, col});
73 | visited[row + 1][col] = 1;
74 | }
75 | }
76 | }
77 |
78 | void atlanticBFS(int row, int col, vector>& heights, vector>& visited, vector>& ans) {
79 |
80 | int m = heights.size();
81 | int n = heights[0].size();
82 |
83 | if(visited[row][col] == 2) {
84 | return;
85 | }
86 |
87 | queue> pq;
88 |
89 | pq.push({row, col});
90 | if(visited[row][col] == 1) {
91 | ans.push_back({row, col});
92 | }
93 | visited[row][col] = 2;
94 |
95 | while(!pq.empty()) {
96 |
97 | pair current = pq.front(); pq.pop();
98 |
99 | int row = current.first;
100 | int col = current.second;
101 | int height = heights[row][col];
102 |
103 | // top
104 | if(row > 0 && visited[row - 1][col] != 2 && heights[row - 1][col] >= height) {
105 | pq.push({row - 1, col});
106 | if(visited[row - 1][col] == 1) {
107 | ans.push_back({row - 1, col});
108 | }
109 | visited[row - 1][col] = 2;
110 | }
111 |
112 | // left
113 | if(col > 0 && visited[row][col - 1] != 2 && heights[row][col - 1] >= height) {
114 | pq.push({row, col - 1});
115 | if(visited[row][col - 1] == 1) {
116 | ans.push_back({row, col - 1});
117 | }
118 | visited[row][col - 1] = 2;
119 | }
120 |
121 | // right
122 | if(col < n - 1 && visited[row][col + 1] != 2 && heights[row][col + 1] >= height) {
123 | pq.push({row, col + 1});
124 | if(visited[row][col + 1] == 1) {
125 | ans.push_back({row, col + 1});
126 | }
127 | visited[row][col + 1] = 2;
128 | }
129 |
130 | // bottom
131 | if(row < m - 1 && visited[row + 1][col] != 2 && heights[row + 1][col] >= height) {
132 | pq.push({row + 1, col});
133 | if(visited[row + 1][col] == 1) {
134 | ans.push_back({row + 1, col});
135 | }
136 | visited[row + 1][col] = 2;
137 | }
138 | }
139 | }
140 |
141 | vector> pacificAtlantic(vector>& heights) {
142 |
143 | int m = heights.size();
144 | int n = heights[0].size();
145 |
146 | vector> visited(m, vector(n, 0));
147 |
148 | // reach of pacific Ocean
149 | // 1
150 |
151 | for(int i = 0; i < n; ++i) {
152 | pacificBFS(0, i, heights, visited);
153 | }
154 | for(int i = 1; i < m; ++i) {
155 | pacificBFS(i, 0, heights, visited);
156 | }
157 |
158 | // reach of Atlantic Ocean
159 | // if cell == 1, include in ans;
160 | // 2
161 |
162 | vector> ans;
163 |
164 | for(int i = 0; i < n; ++i) {
165 | atlanticBFS(m - 1, i, heights, visited, ans);
166 | }
167 | for(int i = 0; i < m; ++i) {
168 | atlanticBFS(i, n - 1, heights, visited, ans);
169 | }
170 |
171 | sort(ans.begin(), ans.end());
172 |
173 | return ans;
174 | }
175 | };
176 | ```
177 |
178 | ### Accepted
179 | [](https://leetcode.com/submissions/detail/628151380/)
180 |
--------------------------------------------------------------------------------
/intuit/split-array-largest-sum.md:
--------------------------------------------------------------------------------
1 | # Split Array Largest Sum
2 |
3 | [](https://leetcode.com/problems/split-array-largest-sum)
4 |
5 | Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.
6 |
7 | Write an algorithm to minimize the largest sum among these m subarrays.
8 |
9 | ### Example 1
10 | ```
11 | Input: nums = [7,2,5,10,8], m = 2
12 | Output: 18
13 | ```
14 |
15 | ### Example 2
16 | ```
17 | Input: nums = [1,2,3,4,5], m = 2
18 | Output: 9
19 | ```
20 |
21 | ### Solution
22 | ```cpp
23 | class Solution {
24 | public:
25 | int minLargestSum(vector& nums, int m, int start, int end, vector& presum, vector>& cache) {
26 | if(m == 1) {
27 | return presum[end] - presum[start];
28 | }
29 | if(cache[start][m] != -1) return cache[start][m];
30 |
31 | int ans = INT_MAX;
32 |
33 | for(int i = start + 1; i <= end - m + 1; ++i) {
34 | int largest_sum = max(
35 | presum[i] - presum[start],
36 | minLargestSum(nums, m - 1, i, end, presum, cache)
37 | );
38 | ans = min(ans, largest_sum);
39 | }
40 |
41 | return cache[start][m] = ans;
42 | }
43 |
44 | int splitArray(vector& nums, int m) {
45 |
46 | vector presum(nums.size() + 1, 0);
47 | vector> cache(nums.size(), vector(m+1, -1));
48 |
49 | for(int i = 0; i < nums.size(); ++i) {
50 | presum[i + 1] = presum[i] + nums[i];
51 | }
52 |
53 | return minLargestSum(nums, m, 0, nums.size(), presum, cache);
54 | }
55 | };
56 | ```
57 |
58 | ### Accepted
59 | [](https://leetcode.com/submissions/detail/625510184/)
60 |
--------------------------------------------------------------------------------
/intuit/word-search.md:
--------------------------------------------------------------------------------
1 | # Word Search
2 |
3 | [](https://practice.geeksforgeeks.org/problems/word-search/1/#)
4 |
5 | Given a 2D board of letters and a word. Check if the word exists in the board. The word can be constructed from letters of adjacent cells only. ie - horizontal or vertical neighbors. The same letter cell can not be used more than once.
6 |
7 | ### Sample Input
8 | ```
9 | 1
10 | 3 4
11 | a g b c
12 | q e e l
13 | g b k s
14 | geeks
15 | ```
16 | ### Sample Output
17 | ```
18 | 1
19 | ```
20 |
21 | ### Solution
22 | ```cpp
23 | class Solution {
24 | public:
25 |
26 | bool findWord(int i, int j, int index, vector>& board, string& word, vector>& visited) {
27 |
28 | if(visited[i][j]) return false;
29 | if(index == word.size()) return true;
30 |
31 | visited[i][j] = 1;
32 |
33 | // up
34 | if(i > 0 && word[index] == board[i-1][j]) {
35 | if(findWord(i-1, j, index + 1, board, word, visited)) {
36 | return true;
37 | }
38 | }
39 |
40 | // down
41 | if(i < board.size()-1 && word[index] == board[i+1][j]) {
42 | if(findWord(i+1, j, index + 1, board, word, visited)) {
43 | return true;
44 | }
45 | }
46 |
47 | // left
48 | if(j > 0 && word[index] == board[i][j-1]) {
49 | if(findWord(i, j-1, index + 1, board, word, visited)) {
50 | return true;
51 | }
52 | }
53 |
54 | // right
55 | if(j < board[0].size()-1 && word[index] == board[i][j+1]) {
56 | if(findWord(i, j+1, index + 1, board, word, visited)) {
57 | return true;
58 | }
59 | }
60 |
61 | visited[i][j] = 0;
62 |
63 | return false;
64 | }
65 |
66 | bool isWordExist(vector>& board, string word) {
67 |
68 | int height = board.size();
69 | int width = board[0].size();
70 |
71 | vector> visited(height, vector(width, 0));
72 |
73 | for(int i = 0; i < height; ++i) {
74 | for(int j = 0; j < width; ++j) {
75 | if(board[i][j] == word[0] && findWord(i, j, 1, board, word, visited)) {
76 | return true;
77 | }
78 |
79 | }
80 | }
81 |
82 | return false;
83 | }
84 | };
85 | ```
86 |
87 | ### Accepted
88 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=67aa95b6421b99e7f44cd0805a9b512b&pid=702088&user=jhasuraj)
89 |
--------------------------------------------------------------------------------
/microsoft/README.md:
--------------------------------------------------------------------------------
1 | # 6Companies30Days Challenge
2 | ## Microsoft
3 |
4 | ### Solved Problems
5 | - [Minimum sum partition](./minimum-sum-partition)
6 | - [Prerequisite Tasks](./prerequisite-tasks.md)
7 | - [Rotate by 90 degree](./rotate-by-90-degree.md)
8 | - [Spirally traversing a matrix](./spirally-traversing-a-matrix.md)
9 | - [Stock span problem](./stock-span-problem.md)
10 | - [Possible Words From Phone Digits](./possible-words-from-phone-digits.md)
11 | - [Unit Area of largest region of 1's](./length-of-largest-region-of-1s.md)
12 | - [Connect Nodes at Same Level](./connect-nodes-at-same-level.md)
13 | - [Count Number of SubTrees having given Sum](./count-number-of-subtrees-having-given-sum.md)
14 | - [Stickler Thief](./stickler-theif.md)
15 | - [Generate Binary Numbers](./generate-binary-numbers.md)
16 | - [Find All Four Sum Numbers](./find-all-four-sum-numbers.md)
17 | - [Bridge edge in a graph](./bridge-edge-in-graph.md)
18 | - [Minimum steps to destination](./minimum-steps-to-destination.md)
19 | - [Alien Dictionary](./alien-dictionary.md)
--------------------------------------------------------------------------------
/microsoft/alien-dictionary.md:
--------------------------------------------------------------------------------
1 | # Alien Dictionary
2 |
3 | [](https://practice.geeksforgeeks.org/problems/alien-dictionary/1/#)
4 |
5 | Given a sorted dictionary of an alien language having N words and k starting alphabets of standard dictionary. Find the order of characters in the alien language.
6 |
7 | **Note:** Many orders may be possible for a particular test case, thus you may return any valid order and output will be 1 if the order of string returned by the function is correct else 0 denoting incorrect string returned.
8 |
9 | ### Sample Input
10 | ```
11 | 6 3
12 | cb ca bb ba ab aa
13 | ```
14 | ### Sample Output
15 | ```
16 | cba
17 | ```
18 |
19 | ### Solution
20 | ```cpp
21 | class Solution {
22 | public:
23 | string topologicalSort(char parent, unordered_map> &G, unordered_set &visited) {
24 | if(visited.count(parent)) return "";
25 |
26 | visited.insert(parent);
27 |
28 | if(G.count(parent) == 0) return string(1, parent);
29 |
30 | string ans = "";
31 | for(auto child: G[parent]) {
32 | ans += topologicalSort(child, G, visited);
33 | }
34 |
35 | ans += parent;
36 |
37 | return ans;
38 | }
39 |
40 | string findOrder(string dict[], int N, int K) {
41 |
42 | unordered_map> G;
43 |
44 | // build graph
45 | for(int i = 1; i < N; ++i) {
46 | int j = 0;
47 | int limit = min(dict[i-1].size(), dict[i].size());
48 |
49 | while(j < limit && dict[i-1][j] == dict[i][j]) ++j;
50 |
51 | if(j < limit) G[dict[i-1][j]].push_back(dict[i][j]);
52 | }
53 |
54 | unordered_set visited;
55 | string ans_rev = "";
56 |
57 | for(auto node: G) {
58 | if(visited.count(node.first)) continue;
59 | ans_rev += topologicalSort(node.first, G, visited);
60 | }
61 |
62 | reverse(ans_rev.begin(), ans_rev.end());
63 |
64 | return ans_rev;
65 | }
66 | };
67 | ```
68 |
69 | ### Accepted
70 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=7ba812bc35c449816be4f5152be73b3b&pid=700494&user=jhasuraj)
71 |
--------------------------------------------------------------------------------
/microsoft/bridge-edge-in-graph.md:
--------------------------------------------------------------------------------
1 | # Bridge edge in a graph
2 |
3 | [](https://practice.geeksforgeeks.org/problems/bridge-edge-in-graph/1#)
4 |
5 | Given a Graph of V vertices and E edges and another edge(c - d), the task is to find if the given edge is a Bridge. i.e., removing the edge disconnects the graph.
6 |
7 | ### Sample Input
8 | ```
9 | 4 4
10 | 0 1
11 | 1 2
12 | 2 3
13 | 1 3
14 | 1 2
15 | ```
16 | ### Sample Output
17 | ```
18 | 0
19 | ```
20 |
21 | ### Solution
22 | ```cpp
23 | class Solution {
24 | public:
25 | int isBridge(int V, vector adj[], int c, int d)
26 | {
27 | vector q1ed(V, false), q2ed(V, false);
28 | queue q1, q2;
29 |
30 | q1.push(c);
31 | q1ed[c] = true;
32 |
33 | q2.push(d);
34 | q2ed[d] = true;
35 |
36 | while(!q1.empty() && !q2.empty()) {
37 | int cReached = q1.front(); q1.pop();
38 | int dReached = q2.front(); q2.pop();
39 |
40 | if(q2ed[cReached] || q1ed[dReached]) {
41 | return 0;
42 | }
43 |
44 | for(auto node: adj[cReached]) {
45 | if(q1ed[node] || (cReached == c && node == d)) continue;
46 | q1.push(node);
47 | q1ed[node] = true;
48 | }
49 |
50 | for(auto node: adj[dReached]) {
51 | if(q2ed[node] || (dReached == d && node == c)) continue;
52 | q2.push(node);
53 | q2ed[node] = true;
54 | }
55 | }
56 | return 1;
57 | }
58 | };
59 | ```
60 |
61 | ### Accepted
62 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=67a1531e0d0963e0b9e76b42c46ea177&pid=700463&user=jhasuraj)
63 |
--------------------------------------------------------------------------------
/microsoft/connect-nodes-at-same-level.md:
--------------------------------------------------------------------------------
1 | # Connect Nodes at Same Level
2 |
3 | [](https://practice.geeksforgeeks.org/problems/connect-nodes-at-same-level/1/#)
4 |
5 | Given a binary tree, connect the nodes that are at same level. You'll be given an addition nextRight pointer for the same.
6 |
7 | Initially, all the nextRight pointers point to garbage values. Your function should set these pointers to point next right for each node.
8 | ```
9 | 10 10-->NULL
10 | / \ / \
11 | 3 5 => 3-->5-->NULL
12 | / \ \ / \ \
13 | 4 1 2 4-->1-->2-->NULL
14 | ```
15 | ### Sample Input
16 | ```
17 | 3 1 2
18 | ```
19 | ### Sample Output
20 | ```
21 | 3 1 2
22 | 1 3 2
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 | void connect(Node *root)
30 | {
31 | queue q;
32 | q.push(root);
33 | q.push(NULL);
34 |
35 | while(!q.empty()) {
36 | Node* node = q.front();
37 | q.pop();
38 |
39 | if(node == NULL) {
40 | if(!q.empty()) {
41 | q.push(NULL);
42 | }
43 | continue;
44 | }
45 |
46 | node->nextRight = q.front();
47 |
48 | if(node->left) q.push(node->left);
49 | if(node->right) q.push(node->right);
50 | }
51 | }
52 | };
53 | ```
54 |
55 | ### Accepted
56 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=5dc3c130ce28f3d5b9fd088b625d5281&pid=700184&user=jhasuraj)
57 |
--------------------------------------------------------------------------------
/microsoft/count-number-of-subtrees-having-given-sum.md:
--------------------------------------------------------------------------------
1 | # Count Number of SubTrees having given Sum
2 |
3 | [](https://practice.geeksforgeeks.org/problems/count-number-of-subtrees-having-given-sum/1/#)
4 |
5 |
6 | Given a binary tree and an integer ``x``. Your task is to complete the function ``countSubtreesWithSumX()`` that returns the count of the number of subtress having total node’s data sum equal to the value ``x``.
7 |
8 | Example: For the tree given below:
9 | ```
10 | 5
11 | / \
12 | -10 3
13 | / \ / \
14 | 9 8 -4 7
15 | ```
16 |
17 | Subtree with sum 7:
18 | ```
19 | -10
20 | / \
21 | 9 8
22 | ```
23 | and one node 7.
24 |
25 | ### Sample Input
26 | ```
27 | 5 -10 3 9 8 -4 7
28 | 7
29 | ```
30 | ### Sample Output
31 | ```
32 | 2
33 | ```
34 |
35 | ### Solution
36 | ```cpp
37 | pair subtreeSum(Node* root, int x) {
38 |
39 | if(root == NULL) return {0, 0};
40 |
41 | int count = 0;
42 |
43 | pair left = subtreeSum(root->left, x);
44 | pair right = subtreeSum(root->right, x);
45 |
46 | count += left.first;
47 | count += right.first;
48 |
49 | int sum = left.second + right.second + root->data;
50 |
51 | if(sum == x) {
52 | ++count;
53 | }
54 |
55 | return {count, sum};
56 | }
57 |
58 | int countSubtreesWithSumX(Node* root, int x)
59 | {
60 | pair result = subtreeSum(root, x);
61 | return result.first;
62 | }
63 | ```
64 |
65 | ### Accepted
66 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=51172c08317c0f21c30621a15a116b2d&pid=700689&user=jhasuraj)
67 |
--------------------------------------------------------------------------------
/microsoft/find-all-four-sum-numbers.md:
--------------------------------------------------------------------------------
1 | # Find All Four Sum Numbers
2 |
3 | [](https://practice.geeksforgeeks.org/problems/find-all-four-sum-numbers1732/1#)
4 |
5 | Given an array of integers and another number. Find all the unique quadruple from the given array that sums up to the given number.
6 |
7 | ### Sample Input
8 | ```
9 | 5 3
10 | 0 0 2 1 1
11 | ```
12 | ### Sample Output
13 | ```
14 | 0 0 1 2 $
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution {
20 | public:
21 | vector > fourSum(vector &arr, int k) {
22 |
23 | unordered_set collection;
24 |
25 | sort(arr.begin(), arr.end());
26 |
27 | int n = arr.size();
28 |
29 | vector> ans;
30 |
31 | for(int i = 0; i < n; ++i) {
32 | for(int j = i+1; j < n; ++j) {
33 |
34 | int l = 0;
35 | int r = n-1;
36 |
37 | while(l < r) {
38 | if(l == i || l == j) {
39 | ++l;
40 | continue;
41 | }
42 | if(r == i || r == j) {
43 | --r;
44 | continue;
45 | }
46 |
47 | int sum = arr[i] + arr[j] + arr[l] + arr[r];
48 |
49 | if(sum == k) {
50 |
51 | vector quadruple = {arr[i], arr[j], arr[l], arr[r]};
52 | sort(quadruple.begin(), quadruple.end());
53 |
54 | string hash = "";
55 | for(int num: quadruple) {
56 | hash += to_string(num) + ':';
57 | }
58 |
59 | if(collection.count(hash) == 0) {
60 | ans.push_back(quadruple);
61 | collection.insert(hash);
62 | }
63 |
64 | ++l;
65 | --r;
66 | }
67 | else if(sum < k) {
68 | ++l;
69 | }
70 | else if(sum > k) {
71 | --r;
72 | }
73 | }
74 | }
75 | }
76 | return ans;
77 | }
78 | };
79 | ```
80 |
81 | ### Accepted
82 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=f27efa8ecab118e23f5489f5a9e4c1bf&pid=702139&user=jhasuraj)
83 |
--------------------------------------------------------------------------------
/microsoft/generate-binary-numbers.md:
--------------------------------------------------------------------------------
1 | # Generate Binary Numbers
2 |
3 | [](https://practice.geeksforgeeks.org/problems/generate-binary-numbers-1587115620/1/#)
4 |
5 | Given a number N. The task is to generate and print all binary numbers with decimal values from 1 to N.
6 |
7 | ### Sample Input
8 | ```
9 | 2
10 | ```
11 | ### Sample Output
12 | ```
13 | 1
14 | 10
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | vector generate(int N) {
20 | vector ans(N);
21 |
22 | for(int i = 1; i <= N; ++i) {
23 | int num = i;
24 | while(num) {
25 | ans[i - 1] += (char) ('0' + (num & 1));
26 | num >>= 1;
27 | }
28 | reverse(ans[i - 1].begin(), ans[i - 1].end());
29 | }
30 |
31 | return ans;
32 | }
33 | ```
34 |
35 | ### Accepted
36 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=e42367210e9eabd08f63daa13922d5a5&pid=701347&user=jhasuraj)
37 |
--------------------------------------------------------------------------------
/microsoft/length-of-largest-region-of-1s.md:
--------------------------------------------------------------------------------
1 | # Unit Area of largest region of 1's
2 |
3 | [](https://practice.geeksforgeeks.org/problems/length-of-largest-region-of-1s-1587115620/1/#)
4 |
5 | Given a grid of dimension nxm containing 0s and 1s. Find the unit area of the largest region of 1s.
6 |
7 | Region of 1's is a group of 1's connected 8-directionally (horizontally, vertically, diagonally).
8 |
9 | ### Sample Input
10 | ```
11 | 3 4
12 | 1 1 1 0
13 | 0 0 1 0
14 | 0 0 0 1
15 | ```
16 |
17 | ### Sample Output
18 | ```
19 | 5
20 | ```
21 |
22 | ### Solution
23 | ```cpp
24 | class Solution {
25 | public:
26 | int calc_area(int r, int c, vector>& grid) {
27 |
28 | int R = grid.size() - 1;
29 | int C = grid[0].size() - 1;
30 |
31 | queue> q;
32 | q.push({r, c});
33 | grid[r][c] = 0;
34 |
35 | int area = 0;
36 |
37 | while(!q.empty()) {
38 | ++area;
39 |
40 | pair block = q.front();
41 | r = block.first;
42 | c = block.second;
43 |
44 | // top
45 | if(r > 0 && grid[r-1][c] == 1) {
46 | q.push({r-1, c});
47 | grid[r-1][c] = 0;
48 | }
49 |
50 | // right
51 | if(c < C && grid[r][c+1] == 1) {
52 | q.push({r, c+1});
53 | grid[r][c+1] = 0;
54 | }
55 |
56 | // bottom
57 | if(r < R && grid[r+1][c] == 1) {
58 | q.push({r+1, c});
59 | grid[r+1][c] = 0;
60 | }
61 |
62 | // left
63 | if(c > 0 && grid[r][c-1] == 1) {
64 | q.push({r, c-1});
65 | grid[r][c-1] = 0;
66 | }
67 |
68 | // topright
69 | if(r > 0 && c < C && grid[r-1][c+1] == 1) {
70 | q.push({r-1, c+1});
71 | grid[r-1][c+1] = 0;
72 | }
73 |
74 | // bottomright
75 | if(r < R && c < C && grid[r+1][c+1] == 1) {
76 | q.push({r+1, c+1});
77 | grid[r+1][c+1] = 0;
78 | }
79 |
80 | // bottomleft
81 | if(r < R && c > 0 && grid[r+1][c-1] == 1) {
82 | q.push({r+1, c-1});
83 | grid[r+1][c-1] = 0;
84 | }
85 |
86 | // topleft
87 | if(r > 0 && c > 0 && grid[r-1][c-1] == 1) {
88 | q.push({r-1, c-1});
89 | grid[r-1][c-1] = 0;
90 | }
91 |
92 | q.pop();
93 | }
94 |
95 | return area;
96 | }
97 |
98 | int findMaxArea(vector>& grid) {
99 | int max_area = 0;
100 | queue q;
101 |
102 | int n = grid.size();
103 | int m = grid[0].size();
104 |
105 | for(int r = 0; r < n; ++r) {
106 | for(int c = 0; c < m; ++c) {
107 | if(grid[r][c]) {
108 | max_area = max(max_area, calc_area(r, c, grid));
109 | }
110 | }
111 | }
112 |
113 | return max_area;
114 | }
115 | };
116 | ```
117 |
118 | ### Accepted
119 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=39b10537fce534f2c18cba0918cff911&pid=701276&user=jhasuraj)
120 |
--------------------------------------------------------------------------------
/microsoft/minimum-steps-to-destination.md:
--------------------------------------------------------------------------------
1 | # Minimum steps to destination
2 |
3 | [](https://practice.geeksforgeeks.org/problems/minimum-number-of-steps-to-reach-a-given-number5234/1/#)
4 |
5 | Given an infinite number line. You start at 0 and can go either to the left or to the right. The condition is that in the ith move, youmust take i steps. Given a destination D , find the minimum number of steps required to reach that destination.
6 |
7 | ### Sample Input
8 | ```
9 | 5
10 | ```
11 | ### Sample Output
12 | ```
13 | 5
14 | ```
15 |
16 | ### Naive Solution
17 | ```cpp
18 | class Solution {
19 | public:
20 | int minSteps(int D, int position = 0, int lastStep = 0) {
21 |
22 | if(abs(position) == D) return 0;
23 | else if(abs(position) > D) return numeric_limits::max();
24 |
25 | return min(
26 | minSteps(D, position + lastStep + 1, lastStep + 1),
27 | minSteps(D, position - lastStep - 1, lastStep + 1)
28 | ) + 1;
29 |
30 | }
31 | };
32 | ```
33 |
34 | ### Solution
35 | ```cpp
36 | class Solution {
37 | public:
38 | int minSteps(int D) {
39 |
40 | int steps = ((double)-1 + sqrt(1 + 8*D)) / (double) 2;
41 | int coverage = (steps * (steps + 1))/2;
42 |
43 | if(coverage == D) return steps;
44 |
45 | for(int i = 0; i < 3; ++i) {
46 | ++steps;
47 | coverage += steps;
48 | if(((coverage - D) & 1) == 0) {
49 | return steps;
50 | }
51 | }
52 | }
53 | };
54 | ```
55 |
56 | ### Accepted
57 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=3f7014dcbd2ec679dc5d04de3334f3d1&pid=704560&user=jhasuraj)
58 |
--------------------------------------------------------------------------------
/microsoft/minimum-sum-partition.md:
--------------------------------------------------------------------------------
1 | # Minimum sum partition
2 |
3 | [](https://practice.geeksforgeeks.org/problems/minimum-sum-partition3317/1/#)
4 |
5 | Given an integer array arr of size N, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum and find the minimum difference
6 |
7 | ### DP Table
8 | 
9 |
10 | ### Sample Input
11 | ```
12 | 8
13 | 5 6 6 5 7 4 7 6
14 | ```
15 | ### Sample Output
16 | ```
17 | 0
18 | ```
19 |
20 | ### Solution
21 | ```cpp
22 | class Solution {
23 |
24 | public:
25 | int minDifference(int arr[], int n) {
26 |
27 | sort(arr, arr+n);
28 |
29 | int sum = accumulate(arr, arr + n, 0);
30 |
31 | int half = sum/2;
32 |
33 | vector< vector > dp(n + 1, vector(half + 1, 0));
34 |
35 | for(int i = 0; i < n; ++i) {
36 | for(int j = 1; j <= half; ++j) {
37 | if(j < arr[i]) {
38 | dp[i+1][j] = dp[i][j];
39 | continue;
40 | }
41 | dp[i+1][j] = max({arr[i], dp[i][j - arr[i]] + arr[i], dp[i][j]});
42 | }
43 | }
44 | return sum - dp.back().back()*2;
45 | }
46 | };
47 | ```
48 |
49 | ### Accepted
50 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=3f5cb6117c6bbc13d452b2aef30dcc85&pid=704140&user=jhasuraj)
51 |
--------------------------------------------------------------------------------
/microsoft/possible-words-from-phone-digits.md:
--------------------------------------------------------------------------------
1 | # Possible Words From Phone Digits
2 |
3 | [](https://practice.geeksforgeeks.org/problems/possible-words-from-phone-digits-1587115620/1/#)
4 |
5 | Given a keypad as shown in the diagram, and an N digit number which is represented by array `a[]`, the task is to list all words which are possible by pressing these numbers.
6 |
7 | 
8 |
9 | ### Sample Input
10 | ```
11 | 3
12 | 2 3 4
13 | ```
14 | ### Sample Output
15 | ```
16 | adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi
17 | ```
18 |
19 | ### Solution
20 | ```cpp
21 | class Solution {
22 | public:
23 | vector possibleWords(int a[], int N, int index = 0) {
24 | vector> keyboard = {
25 | {},
26 | {},
27 | {"a", "b", "c"},
28 | {"d", "e", "f"},
29 | {"g", "h", "i"},
30 | {"j", "k", "l"},
31 | {"m", "n", "o"},
32 | {"p", "q", "r", "s"},
33 | {"t", "u", "v"},
34 | {"w", "x", "y", "z"}
35 | };
36 |
37 | if(index == N - 1) {
38 | return keyboard[a[index]];
39 | }
40 |
41 | vector ans;
42 | vector postfixes = possibleWords(a, N, index + 1);
43 |
44 | for(string c: keyboard[a[index]]) {
45 | for(string s: postfixes) {
46 | ans.push_back(c + s);
47 | }
48 | }
49 |
50 | return ans;
51 | }
52 | };
53 | ```
54 |
55 | ### Accepted
56 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=b5cded5bb9bd33598f54a8cd7fd835a5&pid=701199&user=jhasuraj)
57 |
--------------------------------------------------------------------------------
/microsoft/prerequisite-tasks.md:
--------------------------------------------------------------------------------
1 | # Prerequisite Tasks
2 |
3 | [](https://practice.geeksforgeeks.org/problems/prerequisite-tasks/1/#)
4 |
5 | There are a total of N tasks, labeled from 0 to N-1. Some tasks may have prerequisites, for example to do task 0 you have to first complete task 1, which is expressed as a pair: [0, 1]
6 |
7 | Given the total number of tasks N and a list of prerequisite pairs P, find if it is possible to finish all tasks.
8 |
9 | ### Sample Input
10 | ```
11 | 4
12 | 3
13 | 1 0
14 | 2 1
15 | 3 2
16 | ```
17 | ### Sample Output
18 | ```
19 | Yes
20 | ```
21 |
22 | ### Solution
23 | ```cpp
24 | class Solution {
25 | public:
26 |
27 | bool completeTask(int target, vector> &tasks, vector &state) {
28 |
29 | if(state[target] == 2) {
30 | return true;
31 | }
32 | else if(state[target] == 1) {
33 | return false;
34 | }
35 |
36 | state[target] = 1; // visited
37 |
38 | for(auto task: tasks[target]) {
39 | bool done = completeTask(task, tasks, state);
40 | if(!done) {
41 | return false;
42 | }
43 | }
44 |
45 | state[target] = 2; // completed
46 |
47 | return true;
48 | }
49 |
50 | bool isPossible(int N, vector >& prerequisites) {
51 | vector> tasks(N);
52 | vector state(N, 0);
53 |
54 | for(auto task_pair: prerequisites) {
55 | tasks[task_pair.first].push_back(task_pair.second);
56 | }
57 |
58 | for(int i = 0; i < N; ++i) {
59 | bool done = completeTask(i, tasks, state);
60 | if(!done) {
61 | return false;
62 | }
63 | }
64 |
65 | return true;
66 | }
67 | };
68 | ```
69 |
70 | ### Accepted
71 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=9407a8a44472b1a5dbd29fd22e86ec5c&pid=702128&user=jhasuraj)
72 |
--------------------------------------------------------------------------------
/microsoft/rotate-by-90-degree.md:
--------------------------------------------------------------------------------
1 | # Rotate by 90 degree
2 |
3 | [](https://practice.geeksforgeeks.org/problems/rotate-by-90-degree0356/1/#)
4 |
5 | Given a square matrix[][] of size N x N. The task is to rotate it by 90 degrees in an anti-clockwise direction without using any extra space.
6 |
7 | ### Sample Input
8 | ```
9 | 5
10 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
11 | ```
12 | ### Sample Output
13 | ```
14 | 5 10 15 20 25
15 | 4 9 14 19 24
16 | 3 8 13 18 23
17 | 2 7 12 17 22
18 | 1 6 11 16 21
19 | ```
20 |
21 | ### Solution
22 | ```cpp
23 | void rotate(int n,int a[][n])
24 | {
25 | int limit = (n+1)/2;
26 |
27 | for(int r = 0; r < limit; ++r) {
28 | for(int c = r; c < n-r-1; ++c) {
29 | int temp = a[r][c];
30 | a[r][c] = a[c][n - r - 1];
31 | a[c][n - r - 1] = a[n - r - 1][n - c - 1];
32 | a[n - r - 1][n - c - 1] = a[n - c - 1][r];
33 | a[n - c - 1][r] = temp;
34 | }
35 | }
36 | }
37 | ```
38 |
39 | ### Accepted
40 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=0e64a2357d5660e471a3a6dbd4a922cc&pid=701989&user=jhasuraj)
41 |
--------------------------------------------------------------------------------
/microsoft/spirally-traversing-a-matrix.md:
--------------------------------------------------------------------------------
1 | # Spirally traversing a matrix
2 |
3 | [](https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix-1587115621/1/#)
4 |
5 | Given a matrix of size r*c. Traverse the matrix in spiral form.
6 |
7 | ### Sample Input
8 | ```
9 | 4 4
10 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
11 | ```
12 | ### Sample Output
13 | ```
14 | 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution {
20 | public:
21 | vector spirallyTraverse(vector > M, int r, int c) {
22 | int limit = r*c;
23 | vector ans(limit);
24 |
25 | int x = 0, y = 0, dx = 1, dy = 0, boundary = 0;
26 | int index = 0;
27 |
28 | while(index < limit) {
29 | ans[index++] = M[y][x];
30 |
31 | if(dx == 1 && x == c - boundary - 1) {
32 | dx = 0;
33 | dy = 1;
34 | }
35 |
36 | if(dy == 1 && y == r - boundary - 1) {
37 | dx = -1;
38 | dy = 0;
39 | }
40 |
41 | if(dx == -1 && x == boundary) {
42 | dx = 0;
43 | dy = -1;
44 | }
45 |
46 | if(dy == -1 && y == boundary + 1) {
47 | dx = 1;
48 | dy = 0;
49 | ++boundary;
50 | }
51 |
52 | x += dx;
53 | y += dy;
54 | }
55 | return ans;
56 | }
57 | };
58 | ```
59 |
60 | ### Accepted
61 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=810da18db6144f1c05684e662e7662e0&pid=701264&user=jhasuraj)
62 |
--------------------------------------------------------------------------------
/microsoft/stickler-theif.md:
--------------------------------------------------------------------------------
1 | # Stickler Thief
2 |
3 | [](https://practice.geeksforgeeks.org/problems/stickler-theif-1587115621/1/#)
4 |
5 | Stickler the thief wants to loot money from a society having n houses in a single line. He is a weird person and follows a certain rule when looting the houses. According to the rule, he will never loot two consecutive houses. At the same time, he wants to maximize the amount he loots. The thief knows which house has what amount of money but is unable to come up with an optimal looting strategy. He asks for your help to find the maximum money he can get if he strictly follows the rule. Each house has a[i]amount of money present in it.
6 |
7 | ### Sample Input
8 | ```
9 | 6
10 | 5 5 10 100 10 5
11 | ```
12 |
13 | ### Sample Output
14 | ```
15 | 110
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution {
21 | public:
22 | int FindMaxSum(int arr[], int n)
23 | {
24 | if(n == 1) return arr[0];
25 | if(n == 2) return max(arr[0], arr[1]);
26 |
27 | arr[2] = max(arr[1], arr[0] + arr[2]);
28 |
29 | for(int i = 3; i < n; ++i) {
30 | arr[i] = max({arr[i-1], arr[i-2] + arr[i], arr[i-3] + arr[i]});
31 | }
32 |
33 | return arr[n-1];
34 | }
35 | };
36 | ```
37 |
38 | ### Accepted
39 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=cd0d611d17ad820f079db007fe143235&pid=701417&user=jhasuraj)
40 |
--------------------------------------------------------------------------------
/microsoft/stock-span-problem.md:
--------------------------------------------------------------------------------
1 | # Stock span problem
2 |
3 | [](https://practice.geeksforgeeks.org/problems/stock-span-problem-1587115621/1#)
4 |
5 | The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate the span of stock’s price for all n days.
6 |
7 | The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day.
8 |
9 | For example, if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding 7 days are {1, 1, 1, 2, 1, 4, 6}.
10 |
11 | ### Sample Input
12 | ```
13 | 7
14 | 100 80 60 70 60 75 85
15 | ```
16 |
17 | ### Sample Output
18 | ```
19 | 1 1 1 2 1 4 6
20 | ```
21 |
22 | ### Solution
23 | ```cpp
24 | class Solution {
25 | public:
26 | vector calculateSpan(int price[], int n)
27 | {
28 | stack previous_peak;
29 | previous_peak.push(0);
30 |
31 | vector ans(n);
32 | ans[0] = 1;
33 |
34 | for(int i = 1; i < n; ++i) {
35 | while(!previous_peak.empty() && price[previous_peak.top()] <= price[i]) {
36 | previous_peak.pop();
37 | }
38 |
39 | ans[i] = i - (previous_peak.empty() ? -1 : previous_peak.top());
40 | previous_peak.push(i);
41 | }
42 |
43 | return ans;
44 | }
45 | };
46 | ```
47 |
48 | ### Accepted
49 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=13c879e3f83a1740817b66da69b6e8b6&pid=701342&user=jhasuraj)
--------------------------------------------------------------------------------
/walmart/divide-two-integers.md:
--------------------------------------------------------------------------------
1 | # Divide Two Integers
2 |
3 | [](https://leetcode.com/problems/divide-two-integers/)
4 |
5 | Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
6 |
7 | The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.
8 |
9 | Return the quotient after dividing dividend by divisor.
10 |
11 | **Note:** Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
12 |
13 | ### Example 1
14 | ```
15 | Input: dividend = 10, divisor = 3
16 | Output: 3
17 | ```
18 |
19 | ### Example 2
20 | ```
21 | Input: dividend = 7, divisor = -3
22 | Output: -2
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 | int divide(long long dividend, long long divisor) {
30 |
31 | bool difSign = (dividend > 0ll) ^ (divisor > 0ll);
32 |
33 | dividend = labs(dividend);
34 | divisor = labs(divisor);
35 |
36 | long long quotient = 0;
37 |
38 | while(dividend > 0ll) {
39 | int count = 0;
40 |
41 | while((dividend - (divisor << (count + 1))) >= 0) count++;
42 |
43 | dividend -= divisor << count;
44 |
45 | if(dividend >= 0ll) {
46 | quotient += (1ll << count);
47 | }
48 | }
49 |
50 | return min((difSign ? -quotient : quotient), (long long) 2147483647);
51 | }
52 | };
53 | ```
54 |
55 | ### Accepted
56 | [](https://leetcode.com/submissions/detail/630924752/)
--------------------------------------------------------------------------------
/walmart/find-array-given-subset-sums.md:
--------------------------------------------------------------------------------
1 | # Find Array Given Subset Sums
2 |
3 | [](https://leetcode.com/problems/find-array-given-subset-sums/)
4 |
5 | You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order).
6 |
7 | Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them.
8 |
9 | An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0.
10 |
11 | **Note:** Test cases are generated such that there will always be at least one correct answer.
12 |
13 | ### Example 1
14 | ```
15 | Input: n = 3, sums = [-3,-2,-1,0,0,1,2,3]
16 | Output: [1,2,-3]
17 | ```
18 |
19 | ### Example 2
20 | ```
21 | Input: n = 2, sums = [0,0,0,0]
22 | Output: [0,0]
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 | void print(vector &v) {
30 | for(auto &e: v) {
31 | cout << e << " ";
32 | }
33 | cout << endl;
34 | }
35 | vector array(int n, vector& sums) {
36 | if(n == 1) {
37 | vector result;
38 | if(sums[0] == 0) {
39 | result.push_back(sums[1]);
40 | }
41 | else if(sums[1] == 0) {
42 | result.push_back(sums[0]);
43 | }
44 | return result;
45 | }
46 |
47 | int num = sums[(1 << n) - 1] - sums[(1 << n) - 2];
48 |
49 | unordered_map freq1;
50 | unordered_map freq2;
51 | for(int sum: sums) {
52 | ++freq1[sum];
53 | ++freq2[sum];
54 | }
55 |
56 | // cosider num = |largest negative num|
57 | vector neg;
58 | bool valid_neg = false;
59 | for(auto sum: sums) {
60 | if(freq1.count(sum) && freq1.count(sum + num)) {
61 | if(freq1[sum] > 0) {
62 | neg.push_back(sum + num);
63 | if(sum + num == 0) valid_neg = true;
64 | --freq1[sum];
65 | --freq1[sum + num];
66 | }
67 | }
68 | else {
69 | if(freq1[sum] > 0)
70 | break;
71 | }
72 | }
73 |
74 | if(valid_neg && neg.size() == (1 << (n - 1))) {
75 | vector result = array(n - 1, neg);
76 | result.push_back(-num);
77 | if(result.size() == n)
78 | return result;
79 | }
80 |
81 | // cosider num = |smallest positive num|
82 | vector pos;
83 | bool valid_pos = false;
84 | int limit = (1 << n);
85 | for(int i = 0; i < limit; ++i) {
86 | int sum = sums[limit - 1 - i];
87 | if(freq2.count(sum) && freq2.count(sum - num)) {
88 | if(freq2[sum] > 0) {
89 | pos.push_back(sum - num);
90 | if(sum - num == 0) valid_pos = true;
91 | --freq2[sum];
92 | --freq2[sum - num];
93 | }
94 | }
95 | else {
96 | if(freq2[sum] > 0)
97 | break;
98 | }
99 | }
100 |
101 | if(valid_pos && pos.size() == (1 << (n - 1))) {
102 | reverse(pos.begin(), pos.end());
103 | vector result = array(n - 1, pos);
104 | result.push_back(num);
105 | if(result.size() == n)
106 | return result;
107 | }
108 |
109 | return vector(0);
110 | }
111 |
112 | vector recoverArray(int n, vector& sums) {
113 | sort(sums.begin(), sums.end());
114 | return array(n, sums);
115 | }
116 | };
117 | ```
118 |
119 | ### Accepted
120 | [](https://leetcode.com/submissions/detail/631059018/)
--------------------------------------------------------------------------------
/walmart/find-the-kth-largest-integer-in-the-array.md:
--------------------------------------------------------------------------------
1 | # Find the Kth Largest Integer in the Array
2 |
3 | [](https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/)
4 |
5 | You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.
6 |
7 | Return the string that represents the kth largest integer in nums.
8 |
9 | **Note:** Duplicate numbers should be counted distinctly. For example, if nums is ["1","2","2"], "2" is the first largest integer, "2" is the second-largest integer, and "1" is the third-largest integer.
10 |
11 | ### Example 1
12 | ```
13 | Input: nums = ["3","6","7","10"], k = 4
14 | Output: "3"
15 | ```
16 |
17 | ### Example 2
18 | ```
19 | Input: nums = ["2","21","12","1"], k = 3
20 | Output: "2"
21 | ```
22 |
23 | ### Solution
24 | ```cpp
25 | class Solution {
26 | public:
27 | string kthLargestNumber(vector& nums, int k) {
28 | sort(nums.begin(), nums.end(), [&](string a, string b) {
29 | if(a.size() != b.size()) {
30 | return a.size() < b.size();
31 | }
32 | else {
33 | return a < b;
34 | }
35 | });
36 | for(auto n: nums) cout << n << " ";
37 | return nums.end()[-k];
38 | }
39 | };
40 | ```
41 |
42 | ### Accepted
43 | [](https://leetcode.com/submissions/detail/630107466/)
44 |
--------------------------------------------------------------------------------
/walmart/generate-random-point-in-a-circle.md:
--------------------------------------------------------------------------------
1 | # Generate Random Point in a Circle
2 |
3 | [](https://leetcode.com/problems/generate-random-point-in-a-circle/)
4 |
5 | Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle.
6 |
7 | Implement the Solution class:
8 |
9 | - `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle radius and the position of the center (x_center, y_center).
10 | - `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y].
11 |
12 |
13 | ### Example
14 | ```
15 | Input
16 | ["Solution", "randPoint", "randPoint", "randPoint"]
17 | [[1.0, 0.0, 0.0], [], [], []]
18 | Output
19 | [null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]
20 | ```
21 |
22 | ### Solution
23 | ```cpp
24 | class Solution {
25 | public:
26 | double radius, x_center, y_center;
27 | Solution(double _radius, double _x_center, double _y_center) {
28 | radius = _radius;
29 | x_center = _x_center;
30 | y_center = _y_center;
31 | }
32 |
33 | vector randPoint() {
34 | double theta = ((double) rand()/RAND_MAX)*2*M_PI;
35 | double r = sqrt((double) rand()/RAND_MAX) * radius;
36 | double x = r * cos(theta) + x_center;
37 | double y = r * sin(theta) + y_center;
38 | return {x, y};
39 | }
40 | };
41 | ```
42 |
43 | ### Accepted
44 | [](https://leetcode.com/submissions/detail/630910231/)
45 |
--------------------------------------------------------------------------------
/walmart/guess-number-higher-or-lower-ii.md:
--------------------------------------------------------------------------------
1 | # Guess Number Higher or Lower II
2 |
3 | [](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)
4 |
5 |
6 | ### Example 1
7 | ```
8 | Input: n = 10
9 | Output: 16
10 | ```
11 |
12 | ### Example 2
13 | ```
14 | Input: n = 1
15 | Output: 0
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution {
21 | public:
22 |
23 | int maxAmount(int start, int end, vector> &cache) {
24 | if(end == start) {
25 | return 0;
26 | }
27 | if(end - start == 1) {
28 | return min(start, end);
29 | }
30 | if(cache[start][end] != -1) return cache[start][end];
31 |
32 | int ans = INT_MAX;
33 | for(int i = start + 1; i < end; ++i) {
34 | ans = min(ans, i + max(maxAmount(start, i - 1, cache), maxAmount(i + 1, end, cache)));
35 | }
36 |
37 | cache[start][end] = ans;
38 |
39 | return ans;
40 | }
41 |
42 | int getMoneyAmount(int n) {
43 | vector> cache(n + 1, vector(n + 1, -1));
44 | return maxAmount(1, n, cache);
45 | }
46 | };
47 | ```
48 |
49 | ### Accepted
50 | [](https://leetcode.com/submissions/detail/630897398/)
51 |
--------------------------------------------------------------------------------
/walmart/largest-number-in-k-swaps.md:
--------------------------------------------------------------------------------
1 | # Largest number in K swaps
2 |
3 | [](https://practice.geeksforgeeks.org/problems/largest-number-in-k-swaps-1587115620/1#)
4 |
5 | Given a number K and string str of digits denoting a positive integer, build the largest number possible by performing swap operations on the digits of str at most K times.
6 |
7 | ### Sample Input
8 | ```
9 | 4
10 | 1234567
11 | ```
12 |
13 | ### Sample Output
14 | ```
15 | 7654321
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution {
21 | public:
22 | void swap(char &a, char &b) {
23 | a = a ^ b;
24 | b = a ^ b;
25 | a = a ^ b;
26 | }
27 |
28 | string findMaximumNum(string &str, int k, int index = 0)
29 | {
30 | int length = str.length();
31 |
32 | if(k == 0 || index >= length) {
33 | return str;
34 | }
35 |
36 | int max_index = index;
37 | vector max_indices;
38 |
39 | for(int i = index + 1; i < length; ++i) {
40 | if(str[max_index] <= str[i]) {
41 | if(str[max_index] < str[i]) {
42 | max_indices.clear();
43 | }
44 | max_index = i;
45 | max_indices.push_back(i);
46 | }
47 | }
48 |
49 | if(str[max_index] == str[index]) {
50 | return findMaximumNum(str, k, index + 1);
51 | }
52 |
53 | string ans = str;
54 |
55 | for(int max_index: max_indices) {
56 | swap(str[max_index], str[index]);
57 | ans = max(ans, findMaximumNum(str, k - 1, index + 1));
58 | swap(str[max_index], str[index]);
59 | }
60 |
61 | return ans;
62 | }
63 | };
64 | ```
65 |
66 | ### Accepted
67 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=a2ac5f73bc57db27668984a121f07139&pid=701369&user=jhasuraj)
--------------------------------------------------------------------------------
/walmart/maximum-height-tree.md:
--------------------------------------------------------------------------------
1 | # Maximum Height Tree
2 |
3 | [](https://practice.geeksforgeeks.org/problems/maximum-height-tree4803/1/#)
4 |
5 | Given N dots that form a triangle such that ith line contains i number of dots.
6 | ```
7 | .
8 | . .
9 | . . .
10 | . . . .
11 | ```
12 | Find the minimum hieght H of the triangle that can be formed using these N dots.
13 |
14 | ### Sample Input
15 | ```
16 | 10
17 | ```
18 | ### Sample Output
19 | ```
20 | 4
21 | ```
22 |
23 | ### Solution
24 | ```cpp
25 | class Solution{
26 | public:
27 | int height(int N){
28 | return (-1 + sqrt(1 + 8*N))/2;
29 | }
30 | };
31 | ```
32 |
33 | ### Accepted
34 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=c36067d2317bac4ee2d37ff7e3919c68&pid=705111&user=jhasuraj)
35 |
--------------------------------------------------------------------------------
/walmart/maximum-performance-of-a-team.md:
--------------------------------------------------------------------------------
1 | # Maximum Performance of a Team
2 |
3 | [](https://leetcode.com/problems/maximum-performance-of-a-team/)
4 |
5 | You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively.
6 |
7 | Choose at most k different engineers out of the n engineers to form a team with the maximum performance.
8 |
9 | The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
10 |
11 | Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7.
12 |
13 | ### Example 1
14 | ```
15 | Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2
16 | Output: 60
17 | ```
18 |
19 | ### Example 2
20 | ```
21 | Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3
22 | Output: 68
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 | int maxPerformance(int n, vector& speed, vector& efficiency, int k) {
30 |
31 | vector> eng(n);
32 |
33 | long long int MOD = 1e9+7;
34 |
35 | for(int i = 0; i < n; ++i) {
36 | eng[i].first = efficiency[i];
37 | eng[i].second = speed[i];
38 | }
39 |
40 | sort(eng.rbegin(), eng.rend());
41 |
42 | long long int sum = 0;
43 | long long int ans = INT_MIN;
44 |
45 | priority_queue, greater> heap;
46 |
47 | for(int i = 0; i < k; ++i) {
48 | heap.push(eng[i].second);
49 | sum += eng[i].second;
50 | ans = max(ans, sum*eng[i].first);
51 | }
52 |
53 | for(int i = k; i < n; ++i) {
54 | heap.push(eng[i].second);
55 | sum += eng[i].second;
56 | sum -= heap.top(); heap.pop();
57 | ans = max(ans, sum*eng[i].first);
58 | }
59 |
60 | return ans%MOD;
61 | }
62 | };
63 | ```
64 |
65 | ### Accepted
66 | [](https://leetcode.com/submissions/detail/630982782/)
--------------------------------------------------------------------------------
/walmart/number-of-unique-paths.md:
--------------------------------------------------------------------------------
1 | # Number of Unique Paths
2 |
3 | [](https://practice.geeksforgeeks.org/problems/number-of-unique-paths5339/1/#)
4 |
5 | Given a A X B matrix with your initial position at the top-left cell, find the number of possible unique paths to reach the bottom-right cell of the matrix from the initial position.
6 |
7 | **Note:** Possible moves can be either down or right at any point in time, i.e., we can move to matrix[i+1][j] or matrix[i][j+1] from matrix[i][j].
8 |
9 | ### Sample Input
10 | ```
11 | 4 4
12 | ```
13 |
14 | ### Sample Output
15 | ```
16 | 20
17 | ```
18 |
19 | ### Solution
20 | ```cpp
21 | class Solution
22 | {
23 | public:
24 | int NumberOfPath(int a, int b)
25 | {
26 | vector> M(a, vector(b, 1));
27 |
28 | for(int r = 1; r < a; ++r) {
29 | for(int c = 1; c < b; ++c) {
30 | M[r][c] = M[r-1][c] + M[r][c-1];
31 | }
32 | }
33 |
34 | return M.back().back();
35 | }
36 | };
37 | ```
38 |
39 | ### Accepted
40 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=7bf1795b21916bac65f47e3dc374aa5a&pid=701714&user=jhasuraj)
41 |
--------------------------------------------------------------------------------
/walmart/path-with-maximum-probability.md:
--------------------------------------------------------------------------------
1 | # Path with Maximum Probability
2 |
3 | [](https://leetcode.com/problems/path-with-maximum-probability/)
4 |
5 | You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].
6 |
7 | Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.
8 |
9 | If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.
10 |
11 | ### Example 1
12 | ```
13 | Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
14 | Output: 0.25000
15 | ```
16 |
17 | ### Example 2
18 | ```
19 | Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
20 | Output: 0.30000
21 | ```
22 |
23 | ### Solution
24 | ```cpp
25 | class Solution {
26 | public:
27 | double maxProbability(int n, vector>& edges, vector& prob, int start, int end) {
28 | vector fixed(n, false);
29 | vector ans(n, 0);
30 | ans[start] = 1;
31 |
32 | vector>> graph(n);
33 |
34 | for(int i = 0; i < edges.size(); ++i) {
35 | graph[edges[i][0]].push_back({prob[i], edges[i][1]});
36 | graph[edges[i][1]].push_back({prob[i], edges[i][0]});
37 | }
38 |
39 | priority_queue> pq;
40 |
41 | pq.push({1.0, start});
42 |
43 | while(!pq.empty()) {
44 | pair entry = pq.top(); pq.pop();
45 |
46 | double src_val = entry.first;
47 | int src_node = entry.second;
48 |
49 | if(!fixed[src_node]) {
50 | fixed[src_node] = true;
51 |
52 | for(auto dest: graph[src_node]) {
53 | double probability = dest.first;
54 | int dest_node = dest.second;
55 | if(ans[dest_node] < src_val * probability) {
56 | ans[dest_node] = src_val * probability;
57 | pq.push({ans[dest_node], dest_node});
58 | }
59 | }
60 | }
61 | }
62 |
63 | return ans[end];
64 | }
65 | };
66 | ```
67 |
68 | ### Approach 2 (Error on Test Case 9)
69 | ```cpp
70 | class Solution {
71 | public:
72 | double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) {
73 | vector> prob(n);
74 | for(int i = 0; i < n; ++i) {
75 | prob[i].first = (double) 0.0;
76 | prob[i].second = i;
77 | }
78 | prob[start].first = (double) 1.0;
79 |
80 | // build matrix representation
81 | vector> graph(n, vector(n , (double)0.0));
82 |
83 | for(int i = 0, limit = edges.size(); i < limit; ++i) {
84 | int a = edges[i][0];
85 | int b = edges[i][1];
86 | graph[a][b] = succProb[i];
87 | graph[b][a] = succProb[i];
88 | }
89 |
90 | auto swap_node = [&](int i, int j) {
91 | swap(prob[i], prob[j]);
92 | };
93 |
94 | swap_node(0, start);
95 |
96 | for(int src = 0; src < n - 1; ++src) {
97 | int max = src + 1;
98 |
99 | for(int des = src + 1; des < n; ++des) {
100 | int pos_src = prob[src].second;
101 | int pos_des = prob[des].second;
102 |
103 | double val_des = prob[des].first;
104 | double val_src = prob[src].first;
105 | double probability = graph[pos_src][pos_des];
106 |
107 | if(val_des < val_src * probability) {
108 | prob[des].first = val_src * probability;
109 | if(prob[max].first < prob[des].first) max = des;
110 | }
111 | }
112 | if(prob[max].second == end) {
113 | return prob[max].first;
114 | }
115 | swap_node(max, src + 1);
116 | }
117 |
118 | return 0;
119 | }
120 | };
121 | ```
122 |
123 | ### Accepted
124 | [](https://leetcode.com/submissions/detail/630872979/)
125 |
--------------------------------------------------------------------------------
/walmart/power-of-numbers.md:
--------------------------------------------------------------------------------
1 | # Power Of Numbers
2 |
3 | [](https://practice.geeksforgeeks.org/problems/power-of-numbers-1587115620/1/#)
4 |
5 | Given a number and its reverse. Find that number raised to the power of its own reverse.
6 |
7 | **Note:** As answers can be very large, print the result modulo 109 + 7.
8 |
9 | ### Sample Input
10 | ```
11 | 2
12 | ```
13 | ### Sample Output
14 | ```
15 | 4
16 | ```
17 |
18 | ### Solution
19 | ```cpp
20 | class Solution {
21 | public:
22 | long long MOD = 1e9+7;
23 | long long power(long long N, long long R)
24 | {
25 | N %= MOD;
26 | long long ans = 1;
27 | while (R > 0) {
28 | if (R & 1) {
29 | ans = (ans * N) % MOD;
30 | }
31 | N = (N * N) % MOD;
32 | R >>= 1;
33 | }
34 | return ans;
35 | }
36 | };
37 | ```
38 |
39 | ### Accepted
40 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=485e8401e3cbaf8158dedc3261e361c8&pid=701195&user=jhasuraj)
--------------------------------------------------------------------------------
/walmart/remove-colored-pieces-if-both-neighbors-are-the-same-color.md:
--------------------------------------------------------------------------------
1 | # Remove Colored Pieces if Both Neighbors are the Same Color
2 |
3 | [](link)
4 |
5 | ### Example 1
6 | ```
7 | Input: colors = "AAABABB"
8 | Output: true
9 | ```
10 |
11 | ### Example 2
12 | ```
13 | Input: colors = "AA"
14 | Output: false
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution {
20 | public:
21 |
22 | bool winnerOfGame(string colors) {
23 |
24 | vector A, B;
25 |
26 | char last_color = '-';
27 |
28 | for(char c: colors) {
29 | if(last_color == c) {
30 | if(c == 'A') ++A.back();
31 | else ++B.back();
32 | }
33 | else {
34 | if(c == 'A') A.push_back(1);
35 | else B.push_back(1);
36 | }
37 | last_color = c;
38 | }
39 |
40 | int alice = 0, bob = 0;
41 |
42 | for(int &a: A) alice += max(0, a - 2);
43 |
44 | for(int &b: B) bob += max(0, b - 2);
45 |
46 | return alice > bob;
47 | }
48 | };
49 | ```
50 |
51 | ### Accepted
52 | [](https://leetcode.com/submissions/detail/630887028/)
53 |
--------------------------------------------------------------------------------
/walmart/sorted-subsequence-of-size-3.md:
--------------------------------------------------------------------------------
1 | # Sorted subsequence of size 3
2 |
3 | [](https://practice.geeksforgeeks.org/problems/sorted-subsequence-of-size-3/1/#)
4 |
5 | Given an array A of N integers, find any 3 elements in it such that A[i] < A[j] < A[k] and i < j < k.
6 |
7 | ### Sample Input
8 | ```
9 | 5
10 | 1 2 1 1 3
11 | ```
12 | ### Sample Output
13 | ```
14 | 1 2 3
15 | ```
16 |
17 | ### Solution
18 | ```cpp
19 | class Solution {
20 | public:
21 | vector find3Numbers(vector nums, int N) {
22 | int len = 1;
23 | vector seq(3, INT_MAX), pos(3, -1), mapping(N, -1);
24 | seq[0] = nums[0];
25 | pos[0] = 0;
26 |
27 | for(int i = 1; i < N && len < 3; ++i) {
28 | int index;
29 |
30 | if(seq[len - 1] < nums[i]) {
31 | index = len;
32 | len++;
33 | }
34 | else {
35 | index = lower_bound(seq.begin(), seq.end(), nums[i]) - seq.begin();
36 | }
37 |
38 | seq[index] = nums[i];
39 | pos[index] = i;
40 |
41 | if(index > 0) {
42 | mapping[i] = pos[index - 1];
43 | }
44 | }
45 |
46 | if(len < 3) return vector(0);
47 |
48 | vector result(3, 0);
49 | int ptr = pos[2];
50 | for(int i = 0; i < 3; ++i) {
51 | result[2-i] = nums[ptr];
52 | ptr = mapping[ptr];
53 | }
54 |
55 | return result;
56 | }
57 | };
58 | ```
59 |
60 | ### Accepted
61 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=dae1ec7de9ef9800f03ed13ac19ab231&pid=700357&user=jhasuraj)
--------------------------------------------------------------------------------
/walmart/stone-game.md:
--------------------------------------------------------------------------------
1 | # Stone Game
2 |
3 | [](link)
4 |
5 | Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
6 |
7 | The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties.
8 |
9 | Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.
10 |
11 | Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.
12 |
13 | ### Example 1
14 | ```
15 | Input: piles = [5,3,4,5]
16 | Output: true
17 | ```
18 |
19 | ### Example 2
20 | ```
21 | Input: piles = [3,7,2,3]
22 | Output: true
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 | int maxStone(vector&A,int n, int start, int end, vector>& cache) {
30 |
31 | if(end < start) {
32 | return 0;
33 | }
34 | if(end == start) {
35 | return A[end];
36 | }
37 | if(cache[start][end] != -1) return cache[start][end];
38 |
39 | return cache[start][end] = max({
40 | A[start] + min(maxStone(A, n, start + 2, end, cache), maxStone(A, n, start + 1, end - 1, cache)),
41 | A[end] + min(maxStone(A, n, start, end - 2, cache), maxStone(A, n, start + 1, end - 1, cache))
42 | });
43 | }
44 |
45 | bool stoneGame(vector& piles) {
46 | int n = piles.size();
47 | vector> cache(n, vector(n, -1));
48 | int alice = maxStone(piles, n, 0, n-1, cache);
49 | int bob = accumulate(piles.begin(), piles.end(), 0) - alice;
50 |
51 | return alice > bob;
52 | }
53 | };
54 | ```
55 |
56 | ### Accepted
57 | [](https://leetcode.com/submissions/detail/630880110/)
--------------------------------------------------------------------------------
/walmart/transform-to-sum-tree.md:
--------------------------------------------------------------------------------
1 | # Transform to Sum Tree
2 |
3 | [](https://practice.geeksforgeeks.org/problems/transform-to-sum-tree/1/#)
4 |
5 | Given a Binary Tree of size N , where each node can have positive or negative values. Convert this to a tree where each node contains the sum of the left and right sub trees of the original tree. The values of leaf nodes are changed to 0.
6 |
7 | ### Sample Input
8 | ```
9 | 10
10 | / \
11 | -2 6
12 | / \ / \
13 | 8 -4 7 5
14 | ```
15 |
16 | ### Sample Output
17 | ```
18 | 20
19 | / \
20 | 4 12
21 | / \ / \
22 | 0 0 0 0
23 | ```
24 |
25 | ### Solution
26 | ```cpp
27 | class Solution {
28 | public:
29 | int createSumTree(Node *node) {
30 |
31 | if(node == NULL) return 0;
32 |
33 | int left = createSumTree(node->left);
34 | int right = createSumTree(node->right);
35 | int temp = node->data;
36 | node->data = left + right;
37 |
38 | return (left + right + temp);
39 | }
40 |
41 | void toSumTree(Node *node)
42 | {
43 | createSumTree(node);
44 | }
45 | };
46 | ```
47 |
48 | ### Accepted
49 | [](https://practice.geeksforgeeks.org/viewSol.php?subId=203fa42114545239ef824c0dd52130df&pid=700185&user=jhasuraj)
--------------------------------------------------------------------------------