├── .nojekyll
├── README.md
├── codersbit
├── array-and-prime-divisors.md
├── delete-and-conquer.md
└── scores.md
├── custom.css
├── databases
└── sql-programming
│ ├── actors-and-their-movies.md
│ ├── movie-character.md
│ ├── neutral-reviewers.md
│ └── short-films.md
├── index.html
├── programming
├── arrays
│ ├── add-one-to-number.md
│ ├── anti-diagonals.md
│ ├── find-duplicate-in-array.md
│ ├── find-permutation.md
│ ├── first-missing-integer.md
│ ├── flip.md
│ ├── hotel-bookings-possible.md
│ ├── kth-row-of-pascals-triangle.md
│ ├── largest-number.md
│ ├── max-distance.md
│ ├── max-non-negative-subarray.md
│ ├── max-sum-contiguous-subarray.md
│ ├── maximum-absolute-difference.md
│ ├── maximum-consecutive-gap.md
│ ├── maximum-unsorted-subarray.md
│ ├── maxspprod.md
│ ├── merge-intervals.md
│ ├── merge-overlapping-intervals.md
│ ├── min-steps-in-infinite-grid.md
│ ├── minimum-swaps-2.md
│ ├── n3-repeat-number.md
│ ├── next-permutation.md
│ ├── noble-integer.md
│ ├── pascal-triangle.md
│ ├── repeat-and-missing-number-array.md
│ ├── rotate-matrix.md
│ ├── set-matrix-zeros.md
│ ├── spiral-order-matrix-i.md
│ ├── spiral-order-matrix-ii.md
│ ├── triplets-with-sum-between-given-range.md
│ └── wave-array.md
├── backtracking
│ ├── combination-sum-ii.md
│ ├── combination-sum.md
│ ├── combinations.md
│ ├── generate-all-parentheses-ii.md
│ ├── gray-code.md
│ ├── kth-permutation-sequence.md
│ ├── letter-phone.md
│ ├── nqueens.md
│ ├── palindrome-partitioning.md
│ ├── permutations.md
│ ├── subset.md
│ ├── subsets-ii.md
│ └── sudoku.md
├── binary-search
│ ├── aggressive-cows.md
│ ├── aggressive-cows1.md
│ ├── allocate-books.md
│ ├── count-element-occurence.md
│ ├── cows.md
│ ├── cows2.md
│ ├── implement-power-function.md
│ ├── matrix-median.md
│ ├── matrix-search.md
│ ├── median-of-array.md
│ ├── painters-partition-problem.md
│ ├── rotated-array.md
│ ├── rotated-sorted-array-search.md
│ ├── search-for-a-range-test.md
│ ├── search-for-a-range.md
│ ├── single-element-in-a-sorted-array.md
│ ├── sorted-insert-position.md
│ └── square-root-of-integer.md
├── bit-manipulation
│ ├── different-bits-sum-pairwise.md
│ ├── divide-integers.md
│ ├── min-xor-value.md
│ ├── number-of-1-bits.md
│ ├── reverse-bits.md
│ ├── single-number-ii.md
│ └── single-number.md
├── checkpoints
│ ├── amortized2.md
│ ├── divisor-sequences.md
│ ├── grid-illumination.md
│ ├── intersection-of-linked-lists.md
│ ├── inversions.md
│ ├── kth-smallest-element-in-the-array.md
│ ├── longest-consecutive-sequence.md
│ ├── middle-element-of-linked-list.md
│ ├── next-pointer-binary-tree.md
│ ├── nextgreater.md
│ ├── prettyprint.md
│ ├── reverse-linked-list.md
│ ├── subtract.md
│ ├── unique-binary-search-trees.md
│ └── valid-binary-search-tree.md
├── code-ninja
│ ├── build-identical-trees.md
│ ├── deterministic-finite-automaton.md
│ └── get-mode-array-updates.md
├── dynamic-programming
│ ├── arrange-ii.md
│ ├── best-time-to-buy-and-sell-stocks-i.md
│ ├── best-time-to-buy-and-sell-stocks-ii.md
│ ├── best-time-to-buy-and-sell-stocks-iii.md
│ ├── coin-sum-infinite.md
│ ├── coins-in-a-line.md
│ ├── count-permutations-of-bst.md
│ ├── distinct-subsequences.md
│ ├── dungeon-princess.md
│ ├── edit-distance.md
│ ├── equal-average-partition.md
│ ├── evaluate-expression-to-true.md
│ ├── flip-array.md
│ ├── interleaving-strings.md
│ ├── intersecting-chords-in-a-circle.md
│ ├── jump-game-array.md
│ ├── kingdom-war.md
│ ├── kth-manhattan-distance-neighbourhood.md
│ ├── largest-area-of-rectangle-with-permutations.md
│ ├── length-of-longest-subsequence.md
│ ├── longest-arithmetic-progression.md
│ ├── longest-increasing-subsequence.md
│ ├── longest-valid-parentheses.md
│ ├── max-product-subarray.md
│ ├── max-rectangle-in-binary-matrix.md
│ ├── max-sum-path-in-binary-tree.md
│ ├── max-sum-without-adjacent-elements.md
│ ├── min-jumps-array.md
│ ├── min-sum-path-in-matrix.md
│ ├── min-sum-path-in-triangle.md
│ ├── n-digit-numbers-with-digit-sum-s.md
│ ├── palindrome-partitioning-ii.md
│ ├── queen-attack.md
│ ├── regular-expression-ii.md
│ ├── regular-expression-match.md
│ ├── repeating-sub-sequence.md
│ ├── rod-cutting.md
│ ├── scramble-string.md
│ ├── shortest-common-superstring.md
│ ├── stairs.md
│ ├── sub-matrices-with-sum-zero.md
│ ├── tushars-birthday-bombs.md
│ ├── tushars-birthday-party.md
│ ├── unique-binary-search-trees-ii.md
│ ├── unique-paths-in-a-grid.md
│ ├── ways-to-color-a-3xn-board.md
│ ├── ways-to-decode.md
│ ├── word-break-ii.md
│ └── word-break.md
├── graph-data-structure-and-algorithms
│ ├── black-shapes.md
│ ├── capture-regions-on-board.md
│ ├── clone-graph.md
│ ├── commutable-islands.md
│ ├── convert-sorted-list-to-binary-search-tree.md
│ ├── knight-on-chess-board.md
│ ├── largest-distance-between-nodes-of-a-tree.md
│ ├── level-order.md
│ ├── possibility-of-finishing-all-courses-given-pre-requisites.md
│ ├── smallest-multiple-with-0-and-1.md
│ ├── smallest-sequence-with-given-primes.md
│ ├── stepping-numbers.md
│ ├── sum-of-fibonacci-numbers.md
│ ├── valid-path.md
│ ├── word-ladder-i.md
│ ├── word-ladder-ii.md
│ └── word-search-board.md
├── greedy-algorithm
│ ├── assign-mice-to-holes.md
│ ├── bulbs.md
│ ├── distribute-candy.md
│ ├── gas-station.md
│ ├── highest-product.md
│ ├── majority-element.md
│ └── seats.md
├── hashing
│ ├── 2-sum.md
│ ├── 4-sum.md
│ ├── anagrams.md
│ ├── colorful-number.md
│ ├── copy-list.md
│ ├── diffk-ii.md
│ ├── equal.md
│ ├── fraction.md
│ ├── largest-continuous-sequence-zero-sum.md
│ ├── longest-substring-without-repeat.md
│ ├── points-on-the-straight-line.md
│ ├── substring-concatenation.md
│ ├── valid-sudoku.md
│ └── window-string.md
├── heaps-and-maps
│ ├── distinct-numbers-in-window.md
│ ├── lru-cache.md
│ ├── magician-and-chocolates.md
│ ├── merge-k-sorted-lists.md
│ ├── n-max-pair-combinations.md
│ └── ways-to-form-max-heap.md
├── linked-lists
│ ├── add-two-numbers-as-lists.md
│ ├── insertion-sort-list.md
│ ├── k-reverse-linked-list.md
│ ├── list-cycle.md
│ ├── merge-two-sorted-lists.md
│ ├── palindrome-list.md
│ ├── partition-list.md
│ ├── remove-duplicates-from-sorted-list-ii.md
│ ├── remove-duplicates-from-sorted-list.md
│ ├── remove-nth-element.md
│ ├── remove-nth-node-from-list-end.md
│ ├── reorder-list.md
│ ├── reverse-link-list-ii.md
│ ├── rotate-list.md
│ ├── sort-list.md
│ └── swap-list-nodes-in-pairs.md
├── math
│ ├── all-factors.md
│ ├── city-tour.md
│ ├── excel-column-number.md
│ ├── excel-column-title.md
│ ├── fizzbuzz.md
│ ├── greatest-common-divisor.md
│ ├── grid-unique-paths.md
│ ├── largest-coprime-divisor.md
│ ├── numbers-of-length-n-and-value-less-than-k.md
│ ├── palindrome-integer.md
│ ├── power-of-two-integers.md
│ ├── prime-sum.md
│ ├── rearrange-array.md
│ ├── reverse-integer.md
│ ├── sorted-permutation-rank-with-repeats.md
│ ├── sorted-permutation-rank.md
│ ├── sum-of-pairwise-hamming-distance.md
│ └── trailing-zeros-in-factorial.md
├── random
│ ├── 0-1-string.md
│ ├── anagram-substring-search.md
│ ├── another-chocolate-game.md
│ ├── another-coin-problem.md
│ ├── best-time-to-buy-and-sell-stock-atmost-b-times.md
│ ├── burst-balloons.md
│ ├── bus-and-passenger.md
│ ├── byes.md
│ ├── check-whether-the-graph-is-bipartide-or-not.md
│ ├── common-nodes-in-two-binary-search-trees.md
│ ├── connect-ropes-with-minimum-length.md
│ ├── count-of-pairs-with-the-given-sum.md
│ ├── count-of-range-sum.md
│ ├── count-of-rectangles-with-area-less-than-the-given-number.md
│ ├── count-right-triangles.md
│ ├── custom-sort-string.md
│ ├── design-linked-list.md
│ ├── detect-and-remove-loop-from-a-linked-list.md
│ ├── device-crossover.md
│ ├── edible-strings.md
│ ├── elements-which-have-at-least-two-greater-elements.md
│ ├── falling-dominoes.md
│ ├── falling-squares.md
│ ├── find-a-peak-element.md
│ ├── find-if-there-is-a-sub-array-with-0-sum.md
│ ├── find-sub-array-with-the-given-sum.md
│ ├── find-subsequence.md
│ ├── find-the-next.md
│ ├── first-negative-integer-in-window-size-b.md
│ ├── first-non-repeating-character-in-a-stream-of-characters.md
│ ├── good-subarrays.md
│ ├── grid-unique-paths-ii.md
│ ├── infinite-string.md
│ ├── length-of-longest-consecutive-ones.md
│ ├── lexographically-greater-strings.md
│ ├── longest-pallindromic-subsequence.md
│ ├── matrix-chain-multiplication.md
│ ├── matrix-permutation.md
│ ├── maximise-the-coins-by-popping-balloons.md
│ ├── maximum-frequency-stack.md
│ ├── maximum-height-of-the-staircase.md
│ ├── maximum-product-of-an-increasing-subsequence-of-size-3.md
│ ├── maximum-rectangle.md
│ ├── median-of-stream-of-running-integers.md
│ ├── merge-two-bsts.md
│ ├── minimum-cost-to-hire-k-workers.md
│ ├── minimum-operations-of-given-type-to-make-all-elements-of-a-matrix-equal.md
│ ├── minimum-size-subarray-sum.md
│ ├── minimum-swaps-required-to-bring-all-elements-less-than-or-equal-to-k-together.md
│ ├── most-stones-removed.md
│ ├── n-integers-containing-only-1-2-and-3.md
│ ├── number-of-hosts-per-subnet.md
│ ├── number-of-islands.md
│ ├── palindrome-pairs.md
│ ├── palindromic-substrings-count.md
│ ├── parity-queries.md
│ ├── product-array-puzzle.md
│ ├── reverse-link-list-recursion.md
│ ├── reverse-pairs.md
│ ├── rotten-oranges.md
│ ├── simple-queries.md
│ ├── sort-stack-using-another-stack.md
│ ├── starting-indices-of-the-substrings-in-string.md
│ ├── string-count.md
│ ├── sub-matrix-sum-queries.md
│ ├── subarrays-with-b-different-integers.md
│ ├── subarrays-xor-less-than-b.md
│ ├── sum-of-all-submatrices.md
│ ├── sum-of-minimum-and-maximum-elements-of-all-subarrays-of-size-k.md
│ ├── task-scheduler.md
│ ├── the-square-game.md
│ ├── tiling-problem.md
│ ├── time-based-key-value-store.md
│ ├── top-view.md
│ ├── unreliable-rover.md
│ ├── vertex-cover-problem.md
│ └── wifi-routers.md
├── stacks-and-queues
│ ├── evaluate-expression.md
│ ├── largest-rectangle-in-histogram.md
│ ├── min-stack.md
│ ├── nearest-smaller-element.md
│ ├── rain-water-trapped.md
│ ├── redundant-braces.md
│ ├── simplify-directory-path.md
│ └── sliding-window-maximum.md
├── strings
│ ├── add-binary-strings.md
│ ├── amazing-subarrays.md
│ ├── atoi.md
│ ├── compare-version-numbers.md
│ ├── count-and-say.md
│ ├── implement-strstr.md
│ ├── integer-to-roman.md
│ ├── justified-text.md
│ ├── length-of-last-word.md
│ ├── longest-common-prefix.md
│ ├── longest-palindromic-substring.md
│ ├── minimum-characters-required-to-make-a-string-palindromic.md
│ ├── multiply-strings.md
│ ├── palindrome-string.md
│ ├── power-of-2.md
│ ├── pretty-json.md
│ ├── reverse-the-string.md
│ ├── roman-to-integer.md
│ ├── stringoholics.md
│ ├── valid-ip-addresses.md
│ ├── valid-number.md
│ └── zigzag-string.md
├── time-complexity
│ └── LOOP_CMPL.md
├── tree-data-structure
│ ├── 2-sum-binary-tree.md
│ ├── balanced-binary-tree.md
│ ├── binary-tree-from-inorder-and-postorder.md
│ ├── bst-iterator.md
│ ├── construct-binary-tree-from-inorder-and-preorder.md
│ ├── flatten-binary-tree-to-linked-list.md
│ ├── hotel-reviews.md
│ ├── identical-binary-trees.md
│ ├── inorder-traversal-of-cartesian-tree.md
│ ├── inorder-traversal.md
│ ├── invert-the-binary-tree.md
│ ├── kth-smallest-element-in-tree.md
│ ├── least-common-ancestor.md
│ ├── max-depth-of-binary-tree.md
│ ├── min-depth-of-binary-tree.md
│ ├── next-greater-number-bst.md
│ ├── order-of-people-heights.md
│ ├── path-sum.md
│ ├── populate-next-right-pointers-tree.md
│ ├── postorder-traversal.md
│ ├── preorder-traversal.md
│ ├── recover-binary-search-tree.md
│ ├── root-to-leaf-paths-with-sum.md
│ ├── shortest-unique-prefix.md
│ ├── sorted-array-to-balanced-bst.md
│ ├── sum-root-to-leaf-numbers.md
│ ├── symmetric-binary-tree.md
│ ├── vertical-order-traversal-of-binary-tree.md
│ └── zigzag-level-order-traversal-bt.md
└── two-pointers
│ ├── 3-sum-zero.md
│ ├── 3-sum.md
│ ├── array-3-pointers.md
│ ├── container-with-most-water.md
│ ├── counting-triangles.md
│ ├── diffk.md
│ ├── intersection-of-sorted-arrays.md
│ ├── max-continuous-series-of-1s-my.md
│ ├── max-continuous-series-of-1s.md
│ ├── merge-two-sorted-lists-ii.md
│ ├── minimize-the-absolute-difference.md
│ ├── remove-duplicates-from-sorted-array-ii.md
│ ├── remove-duplicates-from-sorted-array.md
│ ├── remove-element-from-array.md
│ └── sort-by-color.md
├── puzzles
├── arrange-cubes.md
├── cross-the-bridge-ii.md
├── cross-the-bridge.md
├── ratio-of-boys-and-girls.md
└── world-trips.md
└── scripting
├── basic-shell-commands
├── grep.md
├── lines-in-a-given-range.md
├── remove-punctuations.md
├── transform-csv.md
└── valid-phone-number.md
└── regex-and-functions
├── convert-integer-to-roman-number.md
├── sort-by-frequency.md
├── swap-forward-and-backward-slash.md
└── valid-email-address.md
/.nojekyll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/.nojekyll
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # InterviewBit
2 |
3 | InterviewBit problems and C++ solutions collection in HTML5
4 |
5 | ## Live demo
6 |
7 | https://joric.github.io/interviewbit
8 |
9 | ## 3rd-party libs
10 |
11 | * [Marked](https://github.com/markedjs/marked) for the client-side Markdown rendering
12 | * [Prism](https://github.com/PrismLibrary/Prism) for the client-side C++ highlighting
13 |
14 | No jQuery or React or Vue, all in Vanilla JavaScript.
15 |
16 | ## Usage
17 |
18 | * ESC or Ctrl+F - toggle expand / collapse
19 | * → - next problem
20 | * ← - previous problem
21 |
22 | You also can run `index.html` without a server:
23 |
24 | * Chrome: use `--allow-file-access-from-files` command line option
25 | * Firefox: `about:config`, `security.fileuri.strict_origin_policy=false`
26 | * Edge: works with default settings
27 |
28 | For editing Markdown files locally I recommend [Markdown Viewer](https://chrome.google.com/webstore/detail/markdown-viewer/ckkdlimhmcjmikdlpkmbgfkaikojcbjk)
29 | (Chrome plugin).
30 |
31 | ## Copyrights
32 |
33 | All possible copyrights belong to https://www.interviewbit.com
34 |
35 | This is probably the most complete offline collection up to date (~300 documents).
36 |
37 | No web scraping involved, everything is rewritten and/or solved by my bare hands.
38 |
39 | 
40 |
41 | (Got to 5th place!)
42 |
43 | ## References
44 |
45 | * https://joric.github.io/interviewbit
46 | * https://github.com/markedjs/marked
47 | * https://github.com/PrismLibrary/Prism
48 |
--------------------------------------------------------------------------------
/codersbit/scores.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/codersbit/scores.md
--------------------------------------------------------------------------------
/databases/sql-programming/actors-and-their-movies.md:
--------------------------------------------------------------------------------
1 | # Actors and their Movies
2 |
3 | https://www.interviewbit.com/problems/actors-and-their-movies/
4 |
5 | Write a SQL Query to find the name of those movies where one or more actors acted in two or more movies.
6 |
7 | ### Output Schema
8 |
9 | ```
10 | movie_title
11 | ```
12 |
13 | NOTE:
14 |
15 | 1. Output column name has to match the given output schema.
16 | 2. Any name is the concatenation(without any delimiter) of first and last name if present
17 | 3. (E.g. if director_first_name is 'Alfred' and director_last_name is 'Hitchcock' then director_name is 'AlfredHitchcock')
18 |
19 | ### Example Output
20 |
21 | ```
22 | movie_title
23 | Vertigo
24 | ```
25 |
26 | ### Schema Design
27 |
28 | 
29 |
30 | ### Solution
31 | ```sql
32 | select movie_title
33 | from movies where movie_id in
34 | (select movie_id from movies_cast where actor_id in
35 | (select actor_id from movies_cast group by actor_id having count(movie_id)>=2));
36 | ```
37 |
--------------------------------------------------------------------------------
/databases/sql-programming/movie-character.md:
--------------------------------------------------------------------------------
1 | # Movie Character
2 |
3 | https://www.interviewbit.com/problems/movie-character/
4 |
5 |
6 | Write a SQL Query to find the movie_title and name of director (first and last names combined) who directed a movie that casted a role as 'SeanMaguire'.
7 |
8 | ### Output Schema
9 | ```
10 | director_name,movie_title
11 | ```
12 | NOTE:
13 |
14 | Output column name has to match the given output schema.
15 | Any name is the concatenation(without any delimiter) of first and last name if present
16 | (E.g. if director_first_name is 'Alfred' and director_last_name is 'Hitchcock' then director_name is 'AlfredHitchcock')
17 |
18 | ### Example Output
19 |
20 | ```
21 | director_name,movie_title
22 | AlfredHitchcock,Vertigo
23 | ```
24 |
25 | ### Schema Design
26 |
27 | 
28 |
29 | ## Solution
30 | ```sql
31 | select concat(directors.director_first_name,director_last_name) as director_name,movies.movie_title
32 | from movies join movies_directors on movies.movie_id=movies_directors.movie_id
33 | join movies_cast on movies_cast.movie_id=movies.movie_id
34 | join directors on movies_directors.director_id=directors.director_id
35 | where movies_cast.role="SeanMaguire";
36 | ```
37 |
--------------------------------------------------------------------------------
/databases/sql-programming/neutral-reviewers.md:
--------------------------------------------------------------------------------
1 | # Neutral Reviewers
2 |
3 | https://www.interviewbit.com/problems/neutral-reviewers/
4 |
5 | Write a SQL Query to find the name of all reviewers who have rated their ratings with a NULL value.
6 |
7 | Output Schema:
8 |
9 | reviewer_name
10 |
11 | NOTE: Output column name has to match the given output schema.
12 |
13 | Example Output:
14 | ```
15 | reviewer_name
16 | MaxPlank
17 | NeilsBohr
18 | Schrodinger
19 | ```
20 |
21 | 
22 |
23 | ## Solution
24 | ### Editorial
25 |
26 | ```sql
27 | SELECT r.reviewer_name as reviewer_name from reviewers r
28 | INNER JOIN ratings rt
29 | ON rt.reviewer_id = r.reviewer_id
30 | WHERE rt.reviewer_stars IS NULL;
31 | ```
32 |
33 | ### Mine
34 | ```sql
35 | select reviewers.reviewer_name
36 | from reviewers
37 | join ratings
38 | on reviewers.reviewer_id = ratings.reviewer_id and ratings.reviewer_stars is null;
39 | ```
40 |
41 |
42 |
--------------------------------------------------------------------------------
/databases/sql-programming/short-films.md:
--------------------------------------------------------------------------------
1 | # Short Films
2 |
3 | https://www.interviewbit.com/problems/short-films/
4 |
5 | Write a SQL Query to find those lowest duration movies along with the year, director's name(first and last name combined), actor's name(first and last name combined) and his/her role in that production.
6 |
7 | ### Output Schema
8 |
9 | ```
10 | movie_title,movie_year,director_name,actor_name,role
11 | ```
12 |
13 | NOTE:
14 |
15 | 1. Output column name has to match the given output schema.
16 | 2. Any name is the concatenation(without any delimiter) of first and last name if present
17 | 3. (E.g. if director_first_name is 'Alfred' and director_last_name is 'Hitchcock' then director_name is 'AlfredHitchcock')
18 |
19 | ### Example Output
20 |
21 | ```
22 | movie_title,movie_year,director_name,actor_name,role
23 | Vertigo,1958,AlfredHitchcock,JamesStewart,JohnFerguson
24 | ```
25 |
26 | ### Schema design
27 |
28 | 
29 |
30 | ## Solution
31 |
32 | ```sql
33 | select m.movie_title, m.movie_year,
34 | concat(d.director_first_name, d.director_last_name) as director_name,
35 | concat(a.actor_first_name, a.actor_last_name) as actor_name, mc.role
36 | from
37 | movies m join movies_cast mc on m.movie_id = mc.movie_id
38 | join movies_directors md on md.movie_id = m.movie_id
39 | join directors d on md.director_id = d.director_id
40 | join actors a on mc.actor_id = a.actor_id
41 | order by m.movie_time asc limit 1
42 | ```
43 |
--------------------------------------------------------------------------------
/programming/arrays/anti-diagonals.md:
--------------------------------------------------------------------------------
1 | # Anti-Diagonals
2 |
3 | https://www.interviewbit.com/problems/anti-diagonals/
4 |
5 | Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details.
6 |
7 | Example:
8 |
9 | ```
10 | Input:
11 |
12 | 1 2 3
13 | 4 5 6
14 | 7 8 9
15 |
16 | Return the following :
17 |
18 | [
19 | [1],
20 | [2, 4],
21 | [3, 5, 7],
22 | [6, 8],
23 | [9]
24 | ]
25 |
26 |
27 | Input :
28 | 1 2
29 | 3 4
30 |
31 | Return the following :
32 |
33 | [
34 | [1],
35 | [2, 3],
36 | [4]
37 | ]
38 | ```
39 |
40 | ## Hint 1
41 |
42 | Lets look at how the co-ordinates change when you move from one element to the other in the anti-diagonal.
43 |
44 | With every movement, row increases by one, and the column decreases by one ( or in other words (1, -1) gets added to the current co-ordinates ).
45 |
46 | Now, all we need to know is the start ( or the first element ) in each diagonal.
47 |
48 | Can you figure out which elements qualify as the first elements in each diagonal ?
49 |
50 | ## Solution
51 |
52 | ```cpp
53 |
54 | vector > Solution::diagonal(vector > &A) {
55 | vector> result;
56 | vector diagonal;
57 |
58 | int n = A.size();
59 | if(n == 0)
60 | return result;
61 | for(int d = 0; d <= 2*(n-1); d++) {
62 | for(int i = 0; i <= d; i++) {
63 | int j = d - i;
64 | //continue if i or j exceeds their bounds
65 | if(i >= n || j >= n)
66 | continue;
67 | diagonal.push_back(A[i][j]);
68 | }
69 | result.push_back(diagonal);
70 | diagonal.clear();
71 | }
72 | return result;
73 | }
74 |
75 | /*
76 | vector > Solution::diagonal(vector > &A) {
77 | int n = A.size();
78 | int N = 2*(n-1) + 1;//number of vectors in ans
79 | vector> ans(N);
80 | for(int i = 0;i &A) {
43 | int x = 0;
44 | int y = A[0];
45 | for (int i = 1; i < A.size(); i++) {
46 | x ^= i;
47 | y ^= A[i];
48 | }
49 | return x^y;
50 | }
51 | ```
52 |
53 | ### Mine
54 | ```cpp
55 | int Solution::repeatedNumber(const vector &A) {
56 | int k=1;
57 | int i=2;
58 | int n=A.size();
59 |
60 | while(i<=n-1) {
61 | k=k^i;
62 | i+=1;
63 | }
64 |
65 | int temp = A[0];
66 | for(int j=1; j &arrive, vector &depart, int K) {
7 |
8 | sort(arrive.begin(), arrive.end());
9 | sort(depart.begin(), depart.end());
10 |
11 | for (int i=0, j=0, c=0; iK)
17 | return false;
18 | }
19 |
20 | return true;
21 | }
22 |
23 | /*
24 |
25 | // The idea is store arrival and departure times in an auxiliary array with an additional marker
26 | // to indicate whether the time is arrival or departure. Now sort the array. Process the sorted
27 | // array, for every arrival increment active bookings. And for every departure, decrement.
28 | // Keep track of maximum active bookings. If the count of active bookings at any moment
29 | // is more than k, then return false. Else return true.
30 |
31 | bool Solution::hotel(vector &arrive, vector &depart, int K) {
32 | vector > ans;
33 |
34 | int n = arrive.size();
35 |
36 | // create a common vector both arrivals
37 | // and departures.
38 | for (int i = 0; i < n; i++) {
39 | ans.push_back(make_pair(arrive[i], 1));
40 | ans.push_back(make_pair(depart[i], 0));
41 | }
42 |
43 | // sort the vector
44 | sort(ans.begin(), ans.end());
45 |
46 | int curr_active = 0, max_active = 0;
47 |
48 | for (int i = 0; i < ans.size(); i++) {
49 |
50 | // if new arrival, increment current
51 | // guests count and update max active
52 | // guests so far
53 | if (ans[i].second == 1) {
54 | curr_active++;
55 | max_active = max(max_active,
56 | curr_active);
57 | }
58 |
59 | // if a guest departs, decrement
60 | // current guests count.
61 | else
62 | curr_active--;
63 | }
64 |
65 | // if max active guests at any instant
66 | // were more than the available rooms,
67 | // return false. Else return true.
68 | return (K >= max_active);
69 | }
70 | */
71 | ```
72 |
73 |
--------------------------------------------------------------------------------
/programming/arrays/kth-row-of-pascals-triangle.md:
--------------------------------------------------------------------------------
1 | # Kth Row of Pascal's Triangle
2 |
3 | https://www.interviewbit.com/problems/kth-row-of-pascals-triangle/
4 |
5 | Given an index k, return the kth row of the Pascal's triangle.
6 |
7 | Pascal's triangle: To generate A[C] in row R, sum up A'[C] and A'[C-1] from previous row R - 1.
8 |
9 | Example:
10 |
11 | Input: k = 3
12 |
13 | Return: [1,3,3,1]
14 |
15 | NOTE: k is 0 based. k = 0, corresponds to the row [1].
16 |
17 | Note:Could you optimize your algorithm to use only O(k) extra space?
18 |
19 | ## Hint 1
20 |
21 | You just need to follow the formula given in statement.
22 |
23 | It's easy to do it in time complexity of O(k^2).
24 |
25 | You can solve the problem in O(k^2) space but can you see the formula again and try to figure out which extra space you can ignore.
26 |
27 | ## Solution Approach
28 |
29 | Did you account for base cases like numRows = 0, numRows = 1 ?
30 |
31 | Take a look at how we can approach this problem.
32 |
33 | Notice that the first and last numbers in each row ( for row >= 2 ) are 1 and 1.
34 |
35 | For all the other numbers:
36 |
37 | num at position i = number at position i in prev row + number at position (i + 1) in previous row.
38 |
39 | Also, notice that for a row, you only need the value in the previous rows.
40 |
41 | The values in i-2 row do not matter.
42 |
43 | As such, all you need is to maintain 2 vectors and alternate between them.
44 |
45 |
46 | ## Solution
47 |
48 | ```cpp
49 |
50 | vector Solution::getRow(int A) {
51 | vector r(A+1);
52 | r[0] = 1;
53 | int a = 1;
54 | for(int i=1; i<=A; i++){
55 | a = (a*(A-i+1)/i);
56 | r[i] = a;
57 | }
58 | return r;
59 | }
60 |
61 | /*
62 | vector Solution::getRow(int A) {
63 | A+=1;
64 | vector> r(A);
65 |
66 | for (int i = 0; i < A; i++) {
67 | r[i].resize(i + 1);
68 | r[i][0] = r[i][i] = 1;
69 |
70 | for (int j = 1; j < i; j++)
71 | r[i][j] = r[i - 1][j - 1] + r[i - 1][j];
72 | }
73 |
74 | return r[A-1];
75 | }
76 | */
77 | ```
78 |
--------------------------------------------------------------------------------
/programming/arrays/max-non-negative-subarray.md:
--------------------------------------------------------------------------------
1 | # Max Non-Negative Subarray
2 |
3 | https://www.interviewbit.com/problems/max-non-negative-subarray/
4 |
5 | Find out the maximum sub-array of non negative numbers from an array.
6 | The sub-array should be continuous. That is, a sub-array created by choosing the second and fourth element and skipping the third element is invalid.
7 |
8 | Maximum sub-array is defined in terms of the sum of the elements in the sub-array. Sub-array A is greater than sub-array B if sum(A) > sum(B).
9 |
10 | Example:
11 |
12 | A : [1, 2, 5, -7, 2, 3]
13 |
14 | The two sub-arrays are [1, 2, 5] [2, 3].
15 |
16 | The answer is [1, 2, 5] as its sum is larger than [2, 3]
17 |
18 | NOTE: If there is a tie, then compare with segment's length and return segment which has maximum length
19 |
20 | NOTE 2: If there is still a tie, then return the segment with minimum starting index
21 |
22 |
23 |
24 | ## Solution
25 |
26 | ```cpp
27 | vector Solution::maxset(vector &A) {
28 | int len = A.size();
29 | long long maxSum = 0;
30 | long long curSum = 0;
31 | int startMax = -1;
32 | int endMax = -1;
33 | int start = 0;
34 | int end = 0;
35 | while(end < len) {
36 | if(A[end] >= 0) {
37 | curSum += (long long)A[end];
38 | if(curSum > maxSum) {
39 | maxSum = curSum;
40 | startMax = start;
41 | endMax = end + 1;
42 | } else if(curSum == maxSum) {
43 | if(end + 1 - start > endMax - startMax) {
44 | startMax = start;
45 | endMax = end + 1;
46 | }
47 | }
48 | }else {
49 | start = end + 1;
50 | curSum = 0;
51 | }
52 | end++;
53 | }
54 | vector ans;
55 | ans.clear();
56 | if(startMax == -1 || endMax == -1)
57 | return ans;
58 | for(int i = startMax; i < endMax; ++i)
59 | ans.push_back(A[i]);
60 | return ans;
61 | }
62 | ```
63 |
64 | ## Asked in
65 |
66 | * Google
67 |
--------------------------------------------------------------------------------
/programming/arrays/max-sum-contiguous-subarray.md:
--------------------------------------------------------------------------------
1 | # Max Sum Contiguous Subarray
2 |
3 | https://www.interviewbit.com/problems/max-sum-contiguous-subarray/
4 |
5 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
6 |
7 | For example:
8 |
9 | Given the array [-2,1,-3,4,-1,2,1,-5,4],
10 |
11 | the contiguous subarray [4,-1,2,1] has the largest sum = 6.
12 |
13 | For this problem, return the maximum sum.
14 |
15 | ## Solution
16 |
17 | ```cpp
18 |
19 | // Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
20 | // solution: Kadane's Algorithm
21 | int Solution::maxSubArray(const vector &A) {
22 | int maxSum = A[0], currentSum = A[0], n = A.size();
23 | for (int i=1; i &A) {
24 | // max and min variables as described
25 | // in algorithm.
26 | int max1 = INT_MIN, min1 = INT_MAX;
27 | int max2 = INT_MIN, min2 = INT_MAX;
28 |
29 | int n = A.size();
30 | for (int i = 0; i < n; i++) {
31 |
32 | // Updating max and min variables
33 | // as described in algorithm.
34 | max1 = max(max1, A[i] + i);
35 | min1 = min(min1, A[i] + i);
36 | max2 = max(max2, A[i] - i);
37 | min2 = min(min2, A[i] - i);
38 | }
39 |
40 | // Calculating maximum absolute difference.
41 | return max(max1 - min1, max2 - min2);
42 | }
43 | ```
44 |
--------------------------------------------------------------------------------
/programming/arrays/maxspprod.md:
--------------------------------------------------------------------------------
1 | # MAXSPPROD
2 |
3 | https://www.interviewbit.com/problems/maxspprod/
4 |
5 | You are given an array A containing N integers. The special product of each ith integer in this array is defined as the product of the following:
6 |
7 | **LeftSpecialValue**: For an index i, it is defined as the index j such that A[j]>A[i] (i>j). If multiple A[j]'s are present in multiple positions, the LeftSpecialValue is the maximum value of j.
8 |
9 | **RightSpecialValue**: For an index i, it is defined as the index j such that A[j]>A[i] (j>i). If multiple A[j]'s are present in multiple positions, the RightSpecialValue is the minimum value of j.
10 |
11 | Write a program to find the maximum special product of any integer in the array.
12 |
13 | **Input**: You will receive array of integers as argument to function.
14 |
15 | **Return**: Maximum special product of any integer in the array modulo 1000000007.
16 |
17 | **Note**: If j does not exist, the LeftSpecialValue and RightSpecialValue are considered to be 0.
18 |
19 | **Constraints**: 1 <= N <= 10^5; 1 <= A[i] <= 10^9
20 |
21 |
22 | ## Solution
23 |
24 | ```cpp
25 | int next_bigger(std::vector& v, std::stack& stack, int i){
26 | while(!stack.empty()){
27 | int j = stack.top();
28 | if (v[j] <= v[i]){
29 | stack.pop();
30 | }
31 | else{
32 | stack.push(i);
33 | return j;
34 | }
35 | }
36 | stack.push(i);
37 | return 0;
38 | }
39 |
40 | void right( std::vector& v, std::vector& r ){
41 | stack stack;
42 |
43 | for(int i = v.size() - 1; i >= 0; --i){
44 | r[i] = next_bigger(v, stack, i);
45 | stack.push(i);
46 | }
47 | }
48 |
49 | int Solution::maxSpecialProduct(vector &v) {
50 | vector r(v.size());
51 | right(v, r);
52 |
53 | long mp = 0;
54 | std::stack stack;
55 | for (int i = 0; i < v.size(); ++i)
56 | {
57 | long j = next_bigger(v, stack, i);
58 | long mp_i = j * r[i];
59 | if (mp < mp_i)
60 | {
61 | mp = mp_i;
62 | }
63 | }
64 | return mp % 1000000007;
65 | }
66 | ```
67 |
68 |
--------------------------------------------------------------------------------
/programming/arrays/minimum-swaps-2.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/arrays/minimum-swaps-2.md
--------------------------------------------------------------------------------
/programming/arrays/next-permutation.md:
--------------------------------------------------------------------------------
1 | # Next Permutation
2 |
3 | https://www.interviewbit.com/problems/next-permutation/
4 |
5 | Implement the next permutation, which rearranges numbers into the numerically next greater permutation of numbers.
6 |
7 | If such arrangement is not possible, it must be rearranged as the lowest possible order ie, sorted in an ascending order.
8 |
9 | The replacement must be in-place, do not allocate extra memory.
10 |
11 | Examples:
12 |
13 | 1,2,3 -> 1,3,2
14 |
15 | 3,2,1 -> 1,2,3
16 |
17 | 1,1,5 -> 1,5,1
18 |
19 | 20, 50, 113 -> 20, 113, 50
20 |
21 | Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
22 |
23 | Warning : DO NOT USE LIBRARY FUNCTION FOR NEXT PERMUTATION. Use of Library functions will disqualify your submission retroactively and will give you penalty points.
24 |
25 | ## Hint 1
26 |
27 | You can try out few test cases to see what the pattern is or what exactly is the flow of numbers from initial sequence to final sequence.
28 |
29 | ## Solution Approach
30 |
31 | It might help to write down the next permutation on paper to see how and when the sequence changes.
32 |
33 | You'll realize the following pattern :
34 |
35 | The suffix which gets affected is in a descending order before the change.
36 |
37 | A swap with the smaller element happens and then we reverse the affected suffix.
38 |
39 | 1 2 3 -> 1 3 2 // Suffix being just the 3.
40 |
41 | 1 2 3 6 5 4 -> 1 2 4 3 5 6 // Suffix being 6 5 4 in this case.
42 |
43 | ## Solution
44 |
45 | ### Editorial
46 |
47 | ```cpp
48 | void Solution::nextPermutation(vector &num) {
49 | int len = num.size();
50 | int i, j;
51 | for (i = len - 2; i >= 0; i--)
52 | if (num[i] < num[i + 1])
53 | break;
54 |
55 | if (i == -1) {
56 | reverse(num.begin(), num.end());
57 | return;
58 | }
59 |
60 | for (j = len - 1; j > i; j--)
61 | if (num[j] > num[i])
62 | break;
63 |
64 | swap(num[i], num[j]);
65 | reverse(num.begin() + i + 1, num.end());
66 | return;
67 | }
68 | ```
69 |
70 | ## Asked in
71 |
72 | * Microsoft
73 | * Amazon
74 |
75 |
--------------------------------------------------------------------------------
/programming/arrays/noble-integer.md:
--------------------------------------------------------------------------------
1 | # Noble Integer
2 |
3 | https://www.interviewbit.com/problems/noble-integer/
4 |
5 | Given an integer array, find if an integer p exists in the array such that the number of integers greater than p in the array equals to p
6 | If such an integer is found return 1 else return -1.
7 |
8 | ## Hint 1
9 |
10 | The straightforward approach is to for every element find how many integers are greater than that, and if that matches our given statement then we have our answer.
11 |
12 | Will sorting the array help?
13 |
14 | ## Solution Approach
15 |
16 | First we sort the input array.
17 |
18 | Now, all we have to do is to traverse through each element of the array and check whether it matches our given statement, since the array is sorted we directly know how many elements are greater than that number in the array.
19 |
20 | Note: Please take care of cases, when certain element repeats many times.
21 |
22 | ## Solution
23 |
24 | ```cpp
25 | int Solution::solve(vector &A) {
26 | sort(A.begin(), A.end());
27 | for (int i = 0; i= 2 ) are 1 and 1.
32 |
33 | For all the other numbers:
34 |
35 | num at position i = number at position i in prev row + number at position (i + 1) in previous row.
36 |
37 | ## Solution Approach
38 |
39 |
40 | num at position i = number at position i in prev row + number at position (i + 1) in previous row.
41 |
42 | Now, note that to calculate num at position i, we need the numbers in previous row. Which means it makes sense to create rows in order.
43 |
44 | Create a 2D matrix where Matrix[r] denotes row r.
45 | Now process the rows starting from row number 1.
46 |
47 | Row number 1 is obviously just 1.
48 |
49 | For Row i, Row[i][0] = Row[i][i] = 1. And Row[i][j] = Row[i-1][j] + Row[i-1][j-1], when j belongs to [1, i)
50 |
51 |
52 | ## Solution
53 |
54 | ```cpp
55 | vector > Solution::solve(int A) {
56 | vector> r(A);
57 |
58 | for (int i = 0; i < A; i++) {
59 | r[i].resize(i + 1);
60 | r[i][0] = r[i][i] = 1;
61 |
62 | for (int j = 1; j < i; j++)
63 | r[i][j] = r[i - 1][j - 1] + r[i - 1][j];
64 | }
65 |
66 | return r;
67 | }
68 |
69 | /*
70 | vector > Solution::solve(int n) {
71 | vector> a(n);
72 |
73 | for (int i=0; i>&grid) {
30 | int rows = grid.size ();
31 | int cols = grid[0].size ();
32 |
33 | // Check if row 0 has a 0. Save this info for later.
34 | bool row0Has0 = false;
35 | for (int col = 0; col < cols; col++) {
36 | if (grid[0][col] == 0) {
37 | row0Has0 = true;
38 | }
39 | }
40 |
41 | // Check if col 0 has a 0. Save this info for later.
42 | bool col0Has0 = false;
43 | for (int row = 0; row < rows; row++) {
44 | if (grid[row][0] == 0) {
45 | col0Has0 = true;
46 | }
47 | }
48 |
49 | // Use row 0 and col 0 as storage.
50 | // Loop through grid and save which rows and columns have 0s.
51 | for (int row = 0; row < rows; row++) {
52 | for (int col = 0; col < cols; col++) {
53 | if (grid[row][col] == 0) {
54 | grid[row][0] = 0;
55 | grid[0][col] = 0;
56 | }
57 | }
58 | }
59 |
60 | // Zero out the necessary cells in grid (except for 0th row and 0th col).
61 | for (int row = 1; row < rows; row++) {
62 | for (int col = 1; col < cols; col++) {
63 | if (grid[row][0] == 0 || grid[0][col] == 0) {
64 | grid[row][col] = 0;
65 | }
66 | }
67 | }
68 |
69 | // Zero out the necessary cells in row 0.
70 | if (row0Has0) {
71 | for (int col = 0; col < cols; col++) {
72 | grid[0][col] = 0;
73 | }
74 | }
75 |
76 | // Zero out the necessary cells in col 0.
77 | if (col0Has0) {
78 | for (int row = 0; row < rows; row++) {
79 | grid[row][0] = 0;
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/programming/arrays/spiral-order-matrix-ii.md:
--------------------------------------------------------------------------------
1 | # Spiral Order Matrix II
2 |
3 | https://www.interviewbit.com/problems/spiral-order-matrix-ii/
4 |
5 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
6 |
7 | Example:
8 |
9 | Given n = 3,
10 |
11 | You should return the following matrix:
12 |
13 | ```
14 | [
15 | [ 1, 2, 3 ],
16 | [ 8, 9, 4 ],
17 | [ 7, 6, 5 ]
18 | ]
19 | ```
20 |
21 | ## Solution
22 |
23 | ```cpp
24 | vector > Solution::generateMatrix(int A) {
25 |
26 | int n = A;
27 | vector> result_matrix(n, vector(n));
28 |
29 | // Normal Case
30 | int rowStart = 0;
31 | int rowEnd = n-1;
32 | int colStart = 0;
33 | int colEnd = n-1;
34 | int num = 1;
35 |
36 | while (rowStart <= rowEnd && colStart <= colEnd)
37 | {
38 | for (int i = colStart; i <= colEnd; i ++) // 1. horizonal, left to right
39 | {
40 | result_matrix[rowStart][i] = num ++;
41 | }
42 | rowStart ++;
43 |
44 | for (int i = rowStart; i <= rowEnd; i ++) // 2. vertical, top to bottom
45 | {
46 | result_matrix[i][colEnd] = num ++;
47 | }
48 | colEnd --;
49 |
50 | for (int i = colEnd; i >= colStart; i --) // 3. horizonal, right to left
51 | {
52 | if (rowStart <= rowEnd)
53 | result_matrix[rowEnd][i] = num ++;
54 | }
55 | rowEnd --;
56 |
57 | for (int i = rowEnd; i >= rowStart; i --) // 4. vertical, bottom to top
58 | {
59 | if (colStart <= colEnd)
60 | result_matrix[i][colStart] = num ++;
61 | }
62 | colStart ++;
63 | }
64 |
65 | return result_matrix;
66 | }
67 | ```
--------------------------------------------------------------------------------
/programming/arrays/wave-array.md:
--------------------------------------------------------------------------------
1 | # Wave Array
2 |
3 | https://www.interviewbit.com/problems/wave-array/
4 |
5 | Given an array of integers, sort the array into a wave like array and return it,
6 | In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5 ...
7 |
8 | ## Example
9 |
10 | Given [1, 2, 3, 4]
11 |
12 | One possible answer : [2, 1, 4, 3]
13 |
14 | Another possible answer : [4, 1, 3, 2]
15 |
16 | NOTE : If there are multiple answers possible, return the one thats lexicographically smallest.
17 |
18 | So, in example case, you will return [2, 1, 4, 3]
19 |
20 | ## Hint 1
21 |
22 | Hint 1 : Sorting.
23 | Would it help if the array is sorted in ascending order ?
24 |
25 | ## Solution Approach
26 |
27 | array = {5, 1, 3, 4, 2}
28 |
29 | Sort the above array.
30 |
31 | array = {1, 2, 3, 4, 5}
32 |
33 | Now swap adjacent elemets in pairs.
34 |
35 | swap(1, 2)
36 | swap(3, 4)
37 |
38 | Now, our array = {2, 1, 4, 3, 5}
39 |
40 | and voila!, the array is in the wave form.
41 |
42 |
43 | ## Solution
44 |
45 |
46 | ### Sort and swap adjacent pairs
47 |
48 | ```cpp
49 | vector Solution::wave(vector &A) {
50 | std::sort(A.begin(),A.end());
51 | int n = A.size();
52 | for(int i=0;i Solution::wave(vector &A) {
63 | // O(n) solution
64 | int n = A.size();
65 | nth_element(A.begin(), A.begin() + n/2, A.end()); // O(n)
66 | int median = A[n/2];
67 | // everything greater than median goes even, odd otherwise
68 | int even = 0;
69 | int odd = 1;
70 | vector B(n);
71 | for(int i = 0; i < n ; i++) {
72 | if(A[i] &st, int n, int open, int closed, string s) {
38 | if (closed > open) return;
39 | if (open + closed == n && open == closed)
40 | st.push_back(s);
41 | else if (open + closed < n) {
42 | brackets(st, n, open + 1, closed, s + '(');
43 | brackets(st, n, open, closed + 1, s + ')');
44 | }
45 | }
46 |
47 | vector Solution::generateParenthesis(int n) {
48 | vector res;
49 | brackets(res, 2 * n, 0, 0, "");
50 | return res;
51 | }
52 |
53 | ////////////////////////
54 |
55 | void backtracking(int n, int open, int close, string str, vector &res) {
56 | if (close == n) {
57 | res.emplace_back(str);
58 | return;
59 | } else {
60 | if (open < n) {
61 | str += '(';
62 | backtracking(n, open + 1, close, str, res);
63 | str.pop_back();
64 | }
65 | if (open > close) {
66 | str += ')';
67 | backtracking(n, open, close + 1, str, res);
68 | str.pop_back();
69 | }
70 | }
71 | }
72 |
73 | vector Solution::generateParenthesis(int A) {
74 | vector res;
75 |
76 | if (A > 0)
77 | backtracking(A, 0, 0, "", res);
78 | return res;
79 | }
80 | ```
--------------------------------------------------------------------------------
/programming/backtracking/letter-phone.md:
--------------------------------------------------------------------------------
1 | # Letter Phone
2 |
3 | https://www.interviewbit.com/problems/letter-phone
4 |
5 |
6 | ## Hint 1
7 |
8 | Think about possibilites at any place and move on.
9 |
10 | ## Hint 2
11 |
12 | For every integer, you have 1/3/4 options. Try appending every letter in the option to the string and move forward.
13 | ## Solution
14 |
15 | ```cpp
16 |
17 | /* fastest */
18 |
19 | string mapping[] = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
20 |
21 | void makeCombinations(const string &A, const int pos, const string ¤t, vector &result) {
22 | if (pos >= A.size())
23 | return;
24 | const string &letters = mapping[A[pos] - '0'];
25 | for (const char ch : letters) {
26 | string next = current;
27 | next.push_back(ch);
28 | if (next.size() == A.size()) {
29 | result.push_back(next);
30 | } else {
31 | makeCombinations(A, pos + 1, next, result);
32 | }
33 | }
34 | }
35 |
36 | vector Solution::letterCombinations(string A) {
37 | vector result;
38 | makeCombinations(A, 0, "", result);
39 | return result;
40 | }
41 |
42 | /* my */
43 |
44 | unordered_map h = { { '0', "0" }, { '1', "1" }, { '2', "abc" }, { '3', "def" }, { '4', "ghi" }, { '5', "jkl" }, { '6', "mno" }, { '7', "pqrs" }, { '8', "tuv" }, { '9', "wxyz" } };
45 |
46 | void helper(vector &res, string comb, string &digits, int pos) {
47 | if (pos == digits.size()) {
48 | res.push_back(comb);
49 | return;
50 | }
51 | for (char ch : h[digits[pos]])
52 | helper(res, comb + ch, digits, pos + 1);
53 | }
54 |
55 | vector Solution::letterCombinations(string A) {
56 | if (A.empty())
57 | return {};
58 | vector res;
59 | string comb;
60 | helper(res, comb, A, 0);
61 | return res;
62 | }
63 | ```
--------------------------------------------------------------------------------
/programming/backtracking/permutations.md:
--------------------------------------------------------------------------------
1 | # Permutations
2 |
3 | https://www.interviewbit.com/problems/permutations
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | void helper(vector> &res, vector &set, int pos) {
10 | if (pos == set.size()) {
11 | res.push_back(set);
12 | return;
13 | }
14 | for (int i = pos; i < set.size(); i++) {
15 | swap(set[i], set[pos]);
16 | helper(res, set, pos + 1);
17 | swap(set[i], set[pos]);
18 | }
19 | }
20 |
21 | vector> Solution::permute(vector &A) {
22 | vector> res;
23 | helper(res, A, 0);
24 | return res;
25 | }
26 | ```
--------------------------------------------------------------------------------
/programming/backtracking/subset.md:
--------------------------------------------------------------------------------
1 | # Subset
2 |
3 | https://www.interviewbit.com/problems/subset
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | void helper(vector> &res, vector &A, vector &subset, int index) {
10 | res.push_back(subset);
11 | for (int i = index; i < A.size(); i++) {
12 | subset.push_back(A[i]);
13 | helper(res, A, subset, i+1);
14 | subset.pop_back();
15 | }
16 | }
17 |
18 | vector > Solution::subsets(vector &A) {
19 | sort(A.begin(), A.end());
20 | vector> res;
21 | vector subset;
22 | helper(res, A, subset, 0);
23 | return res;
24 | }
25 |
26 | ```
--------------------------------------------------------------------------------
/programming/binary-search/aggressive-cows.md:
--------------------------------------------------------------------------------
1 | # Aggressive Cows
2 |
3 | https://www.interviewbit.com/problems/aggressive-cows
4 |
5 |
6 | Aggressive cows
7 | Farmer John has built a new long barn, with N stalls.
8 | Given an array of integers A of size N where each element of the array represents the location of the stall,
9 | and an integer B which represent the number of cows.
10 |
11 | His cows don't like this barn layout and become aggressive towards each other once put
12 | into a stall. To prevent the cows from hurting each other, John wants to assign the cows to the stalls,
13 | such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
14 |
15 | ## Solution
16 |
17 | ```cpp
18 |
19 | int cows(vector < int >&A, int x, int cows) {
20 | int n = A.size ();
21 | int cowsplaced = 1, lastpos = A[0];
22 | for (int i = 1; i < n; i++) {
23 | if (A[i] - lastpos >= x) {
24 | if (++cowsplaced == cows)
25 | return 1;
26 | lastpos = A[i];
27 | }
28 | }
29 | return 0;
30 | }
31 |
32 | int Solution::solve(vector &A, int B) {
33 | sort (A.begin(), A.end());
34 | int n = A.size();
35 | int l = 0;
36 | int r = A[n-1] - A[0]+1;
37 | while (r-l>1) {
38 | int m = (l+r)/2;
39 | if (cows(A, m, B))
40 | l = m;
41 | else
42 | r = m;
43 | }
44 | return l;
45 | }
46 | ```
--------------------------------------------------------------------------------
/programming/binary-search/aggressive-cows1.md:
--------------------------------------------------------------------------------
1 | # Aggressive Cows1
2 |
3 | https://www.interviewbit.com/problems/aggressive-cows1
4 |
5 |
6 | Aggressive cows
7 | Farmer John has built a new long barn, with N stalls.
8 | Given an array of integers A of size N where each element of the array represents the location of the stall,
9 | and an integer B which represent the number of cows.
10 |
11 | His cows don't like this barn layout and become aggressive towards each other once put
12 | into a stall. To prevent the cows from hurting each other, John wants to assign the cows to the stalls,
13 | such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
14 |
15 | https://www.interviewbit.com/problems/aggressive-cows/
16 |
17 | https://www.quora.com/What-is-the-correct-approach-to-solve-the-SPOJ-problem-Aggressive-cow/answer/Raziman-T-V
18 |
19 | F(x) = 1 if it is possible to arrange the cows in stalls such that the distance between any two cows is at least x
20 | F(x) = 0 otherwise
21 |
22 | Now it is easy to see that if F(x)=0, F(y)=0 for all y>x. Thus, the problem satisfies the monotonicity condition necessary for binary search. It is also easy to find two values of x which give F(x)=0 and 1 respectively. F(0)=1 trivially since the distance between any two cows is at least 0.
23 |
24 | Now, how do we check whether F(x)=1 for a general value of x? We can do this with a greedy algorithm: Keep placing cows at the leftmost possible stalls such that they are at least x distance away from the last placed cow.
25 |
26 | ## Solution
27 |
28 | ```cpp
29 |
30 | int cows(vector &A, int x, int cows) {
31 | int n = A.size();
32 | int count = 1;
33 | int last = A[0];
34 | for (int i = 1; i < n; i++) {
35 | if (A[i] - last >= x) {
36 | if (++count == cows)
37 | return 1;
38 | last = A[i];
39 | }
40 | }
41 | return 0;
42 | }
43 |
44 | int Solution::solve(vector &A, int B) {
45 | sort (A.begin(), A.end());
46 | int n = A.size();
47 | int l = 0;
48 | int r = A[n-1] - A[0]+1;
49 | while (r-l>1) {
50 | int m = (l+r)/2;
51 | if (cows(A, m, B))
52 | l = m;
53 | else
54 | r = m;
55 | }
56 | return l;
57 | }
58 | ```
--------------------------------------------------------------------------------
/programming/binary-search/cows.md:
--------------------------------------------------------------------------------
1 | # Cows
2 |
3 | https://www.interviewbit.com/problems/cows
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | int func (int num, vector &A, int c) {
10 | int cows = 1, pos = array[0], n = A.size();
11 | for (int i = 1; i < n; i++) {
12 | if (A[i]-pos >= num) {
13 | pos = A[i];
14 | cows++;
15 | if (cows == c)
16 | return 1;
17 | }
18 | }
19 | return 0;
20 | }
21 |
22 | int Solution::solve(vector &A, int B) {
23 | int n = A.size();
24 | int ini = 0, last = A[n - 1], max = -1;
25 | while (last > ini) {
26 | int mid = (ini + last) / 2;
27 | if (func (mid, A, B) == 1) {
28 | if (mid > max)
29 | max = mid;
30 | ini = mid + 1;
31 | }
32 | else
33 | last = mid;
34 | }
35 | return max;
36 | }
37 | ```
--------------------------------------------------------------------------------
/programming/binary-search/cows2.md:
--------------------------------------------------------------------------------
1 | # Cows2
2 |
3 | https://www.interviewbit.com/problems/cows2
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | int F (vector < int >&A, int x, int C) {
10 | //We can always place the first cow in the leftmost stall
11 | int N = pos.size ();
12 | int cowsplaced = 1, lastpos = pos[0];
13 | for (int i = 1; i < N; i++) {
14 | if (A[i] - lastpos >= x) {
15 | if (++cowsplaced == C)
16 | return 1;
17 | lastpos = A[i];
18 | }
19 | }
20 | return 0;
21 | }
22 |
23 | int Solution::solve (vector < int >&A, int B) {
24 | int N = A.size ();
25 | sort (A.begin (), A.end ());
26 | int start = 0, end = A[N - 1] - A[0] + 1, mid;
27 | while (end - start > 1) {
28 | mid = (end + start) >> 1;
29 | (F (A, mid, B) ? start : end) = mid;
30 | }
31 | return start;
32 | }
33 | ```
--------------------------------------------------------------------------------
/programming/binary-search/matrix-median.md:
--------------------------------------------------------------------------------
1 | # Matrix Median
2 |
3 | https://www.interviewbit.com/problems/matrix-median
4 |
5 |
6 |
7 | Given a N cross M matrix in which each row is sorted, find the overall median of the matrix. Assume N*M is odd.
8 |
9 | We cannot use extra memory, so we can't actually store all elements in an array and sort the array.
10 | But since, rows are sorted it must be of some use, right?
11 |
12 | Note that in a row you can binary search to find how many elements are smaller than a value X in O(log M).
13 | This is the base of our solution.
14 |
15 | Say k = N*M/2. We need to find (k + 1)^th smallest element.
16 | We can use binary search on answer. In O(N log M), we can count how many elements are smaller
17 | than X in the matrix.
18 |
19 | So, we use binary search on interval [1, INT_MAX]. So, total complexity is O(30 * N log M).
20 |
21 | Note:
22 | This problem can be solve by using min-heap, but extra memory is not allowed.
23 |
24 | ## Solution
25 |
26 | ```cpp
27 |
28 |
29 | int Solution::findMedian(vector > &A) {
30 | int min = A[0][0], max = A[0][0];
31 | int n = A.size(), m = A[0].size();
32 | for (int i = 0; i < n; ++i) {
33 | if (A[i][0] < min) min = A[i][0];
34 | if (A[i][m-1] > max) max = A[i][m-1];
35 | }
36 |
37 | int element = (n * m + 1) / 2;
38 | while (min < max) {
39 | int mid = min + (max - min) / 2;
40 | int cnt = 0;
41 | for (int i = 0; i < n; ++i)
42 | cnt += upper_bound(&A[i][0], &A[i][m], mid) - &A[i][0];
43 | if (cnt < element)
44 | min = mid + 1;
45 | else
46 | max = mid;
47 | }
48 | return min;
49 | }
50 |
51 | ```
--------------------------------------------------------------------------------
/programming/binary-search/matrix-search.md:
--------------------------------------------------------------------------------
1 | # Matrix Search
2 |
3 | https://www.interviewbit.com/problems/matrix-search
4 |
5 |
6 | Write an efficient algorithm that searches for a value in an m x n matrix.
7 |
8 | This matrix has the following properties:
9 |
10 | Integers in each row are sorted from left to right.
11 | The first integer of each row is greater than or equal to the last integer of the previous row.
12 | ## Solution
13 |
14 | ```cpp
15 |
16 | int Solution::searchMatrix(vector > &matrix, int target) {
17 | int n = matrix.size();
18 | int m = matrix[0].size();
19 | int l = 0, r = m * n - 1;
20 | while (l != r){
21 | int mid = (l + r - 1) >> 1;
22 | if (matrix[mid / m][mid % m] < target)
23 | l = mid + 1;
24 | else
25 | r = mid;
26 | }
27 | return matrix[r / m][r % m] == target;
28 | }
29 |
30 |
31 | int Solution::searchMatrix(vector > &A, int x) {
32 | int r=A.size(),c=A[0].size();
33 | int row=-1;
34 | for(int i=0;i=A[i][0]&&x<=A[i][c-1]){
36 | row=i;
37 | break;
38 | }
39 | }
40 | if(row==-1) return 0;
41 | int low=0,high=c-1;
42 | while(low<=high){
43 | int mid=low+(high-low)/2;
44 | if(A[row][mid]==x) return 1;
45 | if(A[row][mid]
20 | using namespace std;
21 |
22 | struct Solution{ vector searchRange(const vector &A, int B); };
23 |
24 | #define DEBUG
25 |
26 | vector Solution::searchRange(const vector &A, int B) {
27 | auto r = equal_range(A.begin(), A.end(), B);
28 | if (r.first!=A.end() && *r.first!=B)
29 | return {-1, -1};
30 | return { r.first-A.begin(), r.second-A.begin()-1 };
31 | }
32 |
33 | int main() {
34 | Solution s;
35 | //vector res = s.searchRange({ 4, 7, 7, 7, 8, 10, 10 },3);
36 | vector res = s.searchRange({1},1);
37 | cout << res[0] << "," << res[1] << endl;
38 |
39 | }
40 | ```
--------------------------------------------------------------------------------
/programming/binary-search/sorted-insert-position.md:
--------------------------------------------------------------------------------
1 | # Sorted Insert Position
2 |
3 | https://www.interviewbit.com/problems/sorted-insert-position
4 |
5 |
6 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
7 |
8 | You may assume no duplicates in the array.
9 |
10 | Here are few examples.
11 | ```
12 | [1,3,5,6], 5 -> 2
13 | [1,3,5,6], 2 -> 1
14 | [1,3,5,6], 7 -> 4
15 | [1,3,5,6], 0 -> 0
16 | ```
17 |
18 | ## Hint 1
19 |
20 | You need to return the index of least element >= x.
21 |
22 | ## Hint 2
23 |
24 | Note that this is classic binary search. Instead of looking for the element x,
25 | you are looking for the least elements >= x.
26 | ## Solution
27 |
28 | ```cpp
29 |
30 | /* editorial */
31 |
32 | class Solution {
33 | public:
34 | int searchInsert(vector &A, int target) {
35 | int n = A.size();
36 | int start = 0, end = n - 1;
37 | int mid;
38 | while(start <= end){
39 | mid = (start + end) / 2;
40 | if(target == A[mid]){
41 | return mid;
42 | }
43 | else if(target < A[mid]){
44 | end = mid - 1;
45 | }
46 | else{
47 | start = mid + 1;
48 | }
49 | }
50 | return start;
51 | }
52 | };
53 |
54 | /* my solution */
55 |
56 | int Solution::searchInsert(vector &A, int B) {
57 | return lower_bound(A.begin(), A.end(), B) - A.begin();
58 | }
59 | ```
--------------------------------------------------------------------------------
/programming/binary-search/square-root-of-integer.md:
--------------------------------------------------------------------------------
1 | # Square Root Of Integer
2 |
3 | https://www.interviewbit.com/problems/square-root-of-integer
4 |
5 |
6 | Square Root of Integer
7 | Implement int sqrt(int x).
8 | Compute and return the square root of x.
9 | If x is not a perfect square, return floor(sqrt(x))
10 |
11 |
12 | ## Hint 1
13 |
14 | Think about the answer of this a particular number r less than floor(sqrt(x))?
15 |
16 | Answer of the above problem as a function of r will look like `[1,1, ... 1,0,0 ... 0]`.
17 |
18 | Can you use this fact to devise a solution now?
19 |
20 | ## Solution Approach
21 |
22 | Think in terms of binary search.
23 | Let us say S is the answer.
24 | We know that `0 <= S <= x`.
25 | Consider any random number r.
26 | ```
27 | If r*r <= x, S >= r
28 | If r*r > x, S < r.
29 | ```
30 | Maybe try to run a binary search for S.
31 |
32 |
33 | ## Solution
34 |
35 | ### Editorial
36 |
37 | ```cpp
38 |
39 | int Solution::sqrt(int A) {
40 | if (A==0 || A==1) return A;
41 | int start = 0, end = A;
42 | int ans;
43 | while(start<=end) {
44 | int mid = start + (end - start)/2;
45 | if (mid <= A/mid) {
46 | start = mid + 1;
47 | ans = mid;
48 | }
49 | else
50 | end = mid - 1;
51 | }
52 | return ans;
53 | }
54 | ```
55 |
56 | ### Mine
57 | ```cpp
58 | int Solution::sqrt(int x) {
59 | if (x < 2) return x;
60 | int l = 1, r = x, res = 0;
61 | while (l <= r) {
62 | long m = r + (l - r) / 2;
63 | if (m * m == x)
64 | return m;
65 | else if (m * m < x)
66 | l = m + 1, res = m;
67 | else
68 | r = m - 1;
69 | }
70 | return res;
71 | ```
72 |
73 |
--------------------------------------------------------------------------------
/programming/bit-manipulation/different-bits-sum-pairwise.md:
--------------------------------------------------------------------------------
1 | # Different Bits Sum Pairwise
2 |
3 | https://www.interviewbit.com/problems/different-bits-sum-pairwise
4 |
5 | We define f(X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f(2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f(2, 7) = 2.
6 |
7 | You are given an array of N positive integers, A1, A2 ,..., AN.
8 |
9 | Find sum of f(Ai, Aj) for all pairs (i, j) such that 1 <= i, j <= N.
10 |
11 | Return the answer modulo 10^9+7.
12 |
13 | For example,
14 |
15 | A=[1, 3, 5]
16 |
17 | We return
18 | ```
19 | f(1, 1) + f(1, 3) + f(1, 5) +
20 | f(3, 1) + f(3, 3) + f(3, 5) +
21 | f(5, 1) + f(5, 3) + f(5, 5) =
22 |
23 | 0 + 1 + 1 +
24 | 1 + 0 + 2 +
25 | 1 + 2 + 0 = 8
26 | ```
27 |
28 | ## Solution
29 |
30 | ```cpp
31 | int Solution::cntBits(vector &A) {
32 | long ans = 0; // Initialize result
33 | int n = A.size();
34 |
35 | // traverse over all bits
36 | for (int i = 0; i < 32; i++) {
37 | // count number of elements with i'th bit set
38 | long count = 0;
39 | for (int j = 0; j < n; j++)
40 | if ( (A[j] & (1 << i)) )
41 | count++;
42 |
43 | // Add "count * (n - count) * 2" to the answer
44 | ans += (count * (n - count) * 2);
45 | }
46 |
47 | return ans % 1000000007;
48 | }
49 |
50 | ```
51 |
--------------------------------------------------------------------------------
/programming/bit-manipulation/min-xor-value.md:
--------------------------------------------------------------------------------
1 | # Min Xor Value
2 |
3 | https://www.interviewbit.com/problems/min-xor-value
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | int Solution::findMinXor(vector &arr) {
10 | int n = arr.size();
11 | sort(arr.begin(), arr.end());
12 | int minXor = INT_MAX;
13 | int val = 0;
14 | // calculate min xor of consecutive pairs
15 | for (int i = 0; i < n - 1; i++)
16 | minXor = min(minXor, arr[i] ^ arr[i + 1]);
17 |
18 | return minXor;
19 | }
20 | ```
--------------------------------------------------------------------------------
/programming/bit-manipulation/number-of-1-bits.md:
--------------------------------------------------------------------------------
1 | # Number Of 1 Bits
2 |
3 | https://www.interviewbit.com/problems/number-of-1-bits
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | int Solution::numSetBits(unsigned int A) {
10 | // use kernigan
11 | int i;
12 | for (i = 0; A; i++) {
13 | A &= A - 1;
14 | }
15 | return i;
16 | }
17 |
18 | ```
--------------------------------------------------------------------------------
/programming/bit-manipulation/reverse-bits.md:
--------------------------------------------------------------------------------
1 | # Reverse Bits
2 |
3 | https://www.interviewbit.com/problems/reverse-bits
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | unsigned int Solution::reverse(unsigned int A) {
10 | unsigned int res=0;
11 | int i, bit;
12 | for(i=0;i<32;i++) {
13 | bit = (A>>i) & 1;
14 | res = (res<<1) | bit;
15 | }
16 | return res;
17 | }
18 |
19 | unsigned int Solution::reverse(unsigned int A) {
20 | unsigned int res=0;
21 | for(int i=1; i<=32; i++) {
22 | res <<= 1;
23 | res |= A & 1;
24 | A >>= 1;
25 | }
26 | return res;
27 | }
28 |
29 |
30 | unsigned int Solution::reverse(unsigned int b) {
31 | unsigned int out = 0;
32 | int n = 32;
33 |
34 | if (b & 1)
35 | out |= 1;
36 |
37 | for (int i=1; i>= 1;
39 | out <<= 1;
40 | if (b & 1)
41 | out |= 1;
42 | }
43 |
44 | return out;
45 | }
46 |
47 | unsigned int Solution::reverse(unsigned int x) {
48 | x = ((x & 0b11111111111111110000000000000000) >> 16)| ((x & 0b00000000000000001111111111111111) << 16);
49 | x = ((x & 0b11111111000000001111111100000000) >> 8) | ((x & 0b00000000111111110000000011111111) << 8);
50 | x = ((x & 0b11110000111100001111000011110000) >> 4) | ((x & 0b00001111000011110000111100001111) << 4);
51 | x = ((x & 0b11001100110011001100110011001100) >> 2) | ((x & 0b00110011001100110011001100110011) << 2);
52 | x = ((x & 0b10101010101010101010101010101010) >> 1) | ((x & 0b01010101010101010101010101010101) << 1);
53 | return x;
54 | }
55 |
56 | unsigned int Solution::reverse(unsigned int x) {
57 | // order doesn't matter (!)
58 | x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
59 | x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2);
60 | x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4);
61 | x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
62 | x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16);
63 | return x;
64 | }
65 |
66 | unsigned int Solution::reverse(unsigned int b) {
67 | unsigned int out = 0;
68 | int n = 32;
69 | for (int i=0; i &A) {
13 | int ret = 0;
14 | for(int i = 0; i < A.size(); i++)
15 | ret ^= A[i];
16 | return ret;
17 | }
18 |
19 |
20 | /* my solution */
21 |
22 | int Solution::singleNumber(const vector &A) {
23 | int ret = 0;
24 | for(int i = 0; i < A.size(); ret ^= A[i++]);
25 | return ret;
26 | }
27 |
28 | int Solution::singleNumber(const vector &A) {
29 | int sum = A[0];
30 | for (int i=1; i &A, int k) {
31 | int n = A.size();
32 | if (k>n || n==0)
33 | return -1;
34 |
35 | int lo = A[0], hi = A[0];
36 | for (int i=1; i= k)
51 | break;
52 | }
53 |
54 | if (countLess < k && countLess + countEqual >= k)
55 | return mid;
56 | else if (countLess >= k)
57 | hi = mid - 1;
58 | else
59 | lo = mid + 1;
60 | }
61 | return -1;
62 | }
63 | ```
64 |
--------------------------------------------------------------------------------
/programming/checkpoints/longest-consecutive-sequence.md:
--------------------------------------------------------------------------------
1 | # Longest Consecutive Sequence
2 |
3 | https://www.interviewbit.com/problems/longest-consecutive-sequence/
4 |
5 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
6 |
7 | Example:
8 |
9 | Given [100, 4, 200, 1, 3, 2],
10 |
11 | The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
12 |
13 | Your algorithm should run in O(n) complexity.
14 |
15 | ## Solution
16 |
17 | ```cpp
18 | // editorial
19 |
20 | int Solution::longestConsecutive(const vector &v) {
21 | unordered_set h;
22 | for (int x : v)
23 | h.insert(x);
24 |
25 | int longestStreak = 0;
26 |
27 | for (int x : v) {
28 | int currentStreak = 1;
29 | int currentNum = x;
30 |
31 | if (h.count(currentNum - 1) == 0) {
32 | while (h.count(currentNum + 1) != 0) {
33 | currentNum++;
34 | currentStreak++;
35 | }
36 | longestStreak = max(longestStreak, currentStreak);
37 | }
38 | }
39 |
40 | return longestStreak;
41 | }
42 |
43 | // my
44 | int Solution::longestConsecutive(const vector &nums) {
45 | unordered_set num_set;
46 |
47 | for (int num : nums)
48 | num_set.insert(num);
49 |
50 | int longestStreak = 0;
51 |
52 | for (int num : num_set) {
53 | if (!num_set.count(num - 1)) {
54 | int currentNum = num;
55 | int currentStreak = 1;
56 |
57 | while (num_set.count(currentNum + 1)) {
58 | currentNum += 1;
59 | currentStreak += 1;
60 | }
61 |
62 | longestStreak = max(longestStreak, currentStreak);
63 | }
64 | }
65 |
66 | return longestStreak;
67 | }
68 | ```
--------------------------------------------------------------------------------
/programming/checkpoints/middle-element-of-linked-list.md:
--------------------------------------------------------------------------------
1 | # Middle element of linked list
2 |
3 | https://www.interviewbit.com/problems/middle-element-of-linked-list/
4 |
5 | Given a linked list of integers. Find and return the middle element of the linked list.
6 |
7 | Note: If there are N nodes in the linked list and N is even then return the (N/2+1)th element.
8 |
9 | ```
10 | Input Format
11 |
12 | The only argument given head pointer of linked list.
13 | Output Format
14 |
15 | Return the middle element of the linked list.
16 | Constraints
17 |
18 | 1 <= length of the linked list <= 100000
19 | 1 <= Node value <= 10^9
20 | For Example
21 |
22 | Input 1:
23 | 1->2->3->4->5
24 | Output 1:
25 | 3
26 |
27 | Input 2:
28 | A = 1->5->6->2->3->4
29 | Output 2:
30 | 2
31 | ```
32 |
33 | ## Solution
34 |
35 | ### Editorial
36 | ```cpp
37 | int Solution::solve(ListNode* A) {
38 | ListNode* slow=A;
39 | ListNode* fast=A;
40 | while(fast!=NULL && fast->next!=NULL)
41 | {
42 | fast=fast->next->next;
43 | slow=slow->next;
44 | }
45 | return slow->val;
46 | }
47 | ```
48 |
49 | ### Fastest
50 | ```cpp
51 | int Solution::solve(ListNode* A) {
52 | ListNode* slow=A;
53 | ListNode* fast=A;
54 | while(fast!=NULL && fast->next!=NULL)
55 | {
56 | fast=fast->next->next;
57 | slow=slow->next;
58 | }
59 | return slow->val;
60 | }
61 | ```
62 |
63 | ### Lightweight
64 | ```cpp
65 | int Solution::solve(ListNode* A) {
66 | ListNode* slow=A;
67 | ListNode* fast=A;
68 | while(fast&&fast->next)
69 | {
70 | slow=slow->next;
71 | fast=fast->next->next;
72 | }
73 | return slow->val;
74 | }
75 | ```
76 |
77 |
--------------------------------------------------------------------------------
/programming/checkpoints/next-pointer-binary-tree.md:
--------------------------------------------------------------------------------
1 | # Next Pointer Binary Tree
2 |
3 | https://www.interviewbit.com/problems/next-pointer-binary-tree/
4 |
5 | Given a binary tree
6 | ```
7 | struct TreeLinkNode {
8 | TreeLinkNode *left;
9 | TreeLinkNode *right;
10 | TreeLinkNode *next;
11 | }
12 | ```
13 | Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
14 |
15 | Initially, all next pointers are set to NULL.
16 |
17 | Note:
18 | You may only use constant extra space.
19 | You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
20 | Example :
21 |
22 | Given the following perfect binary tree,
23 | ```
24 | 1
25 | / \
26 | 2 5
27 | / \ / \
28 | 3 4 6 7
29 | ```
30 | After calling your function, the tree should look like:
31 | ```
32 | 1 -> NULL
33 | / \
34 | 2 -> 5 -> NULL
35 | / \ / \
36 | 3->4->6->7 -> NULL
37 | ```
38 | Note that using recursion has memory overhead and does not qualify for constant space.
39 |
40 | ## Solution
41 |
42 | ### Editorial
43 | ```cpp
44 | void levelOrderTraversal(TreeLinkNode *root, unordered_map &ret, int depth) {
45 | if (!root)
46 | return;
47 | if (ret[depth])
48 | ret[depth]->next = root;
49 | ret[depth] = root;
50 | levelOrderTraversal(root->left, ret, depth + 1);
51 | levelOrderTraversal(root->right, ret, depth + 1);
52 | }
53 |
54 | void Solution::connect(TreeLinkNode *A) {
55 | unordered_map ret;
56 | levelOrderTraversal(A, ret, 0);
57 | }
58 |
59 | ```
60 |
61 | ### Mine
62 |
63 | ```cpp
64 | void Solution::connect(TreeLinkNode *root) {
65 | for (TreeLinkNode *i = root; i->left; i = i->left) {
66 | for (TreeLinkNode *j = i; j; j = j->next) {
67 | j->left->next = j->right;
68 | if (j->next)
69 | j->right->next = j->next->left;
70 | }
71 | }
72 | }
73 |
74 | ```
75 |
--------------------------------------------------------------------------------
/programming/checkpoints/nextgreater.md:
--------------------------------------------------------------------------------
1 | # NEXTGREATER
2 |
3 | https://www.interviewbit.com/problems/nextgreater/
4 |
5 | Given an array, find the next greater element G[i] for every element A[i] in the array. The Next greater Element for an element A[i] is the first greater element on the right side of A[i] in array.
6 | More formally,
7 | ```
8 | G[i] for an element A[i] = an element A[j] such that
9 | j is minimum possible AND
10 | j > i AND
11 | A[j] > A[i]
12 | ```
13 | Elements for which no greater element exist, consider next greater element as -1.
14 |
15 | Example:
16 |
17 | Input : A : [4, 5, 2, 10]
18 |
19 | Output : [5, 10, 10, -1]
20 |
21 | Example 2:
22 |
23 | Input : A : [3, 2, 1]
24 |
25 | Output : [-1, -1, -1]
26 |
27 |
28 | ## Solution
29 |
30 | ```cpp
31 | vector Solution::nextGreater(vector &A) {
32 | int n = A.size();
33 | vector nG(n);
34 | nG[n - 1] = -1;
35 | for (int i = n - 1; i > 0; i--) {
36 | if (A[i] > A[i - 1]) {
37 | nG[i - 1] = A[i];
38 | } else {
39 | if (A[i - 1] < nG[i]) {
40 | nG[i - 1] = nG[i];
41 | } else {
42 | int j = i;
43 | while (j < n && A[i - 1] >= nG[j++])
44 | ;
45 | nG[i - 1] = nG[j - 1];
46 | }
47 | }
48 | }
49 | return nG;
50 | }
51 | ```
52 |
--------------------------------------------------------------------------------
/programming/checkpoints/prettyprint.md:
--------------------------------------------------------------------------------
1 | # PRETTYPRINT
2 |
3 | https://www.interviewbit.com/problems/prettyprint/
4 |
5 | Print concentric rectangular pattern in a 2d matrix.
6 | Let us show you some examples to clarify what we mean.
7 |
8 | Example 1:
9 |
10 | Input: A = 4.
11 | Output:
12 | ```
13 | 4 4 4 4 4 4 4
14 | 4 3 3 3 3 3 4
15 | 4 3 2 2 2 3 4
16 | 4 3 2 1 2 3 4
17 | 4 3 2 2 2 3 4
18 | 4 3 3 3 3 3 4
19 | 4 4 4 4 4 4 4
20 | ```
21 | Example 2:
22 |
23 | Input: A = 3.
24 | Output:
25 | ```
26 | 3 3 3 3 3
27 | 3 2 2 2 3
28 | 3 2 1 2 3
29 | 3 2 2 2 3
30 | 3 3 3 3 3
31 | ```
32 | The outermost rectangle is formed by A, then the next outermost is formed by A-1 and so on.
33 |
34 | You will be given A as an argument to the function you need to implement, and you need to return a 2D array.
35 |
36 | ## Solution
37 |
38 | ```cpp
39 | // Print concentric rectangular pattern in a 2d matrix
40 |
41 | vector > Solution::prettyPrint(int A) {
42 | int n = A*2 - 1;
43 | vector> v(n, vector(n));
44 | for (int i=0; idy ? dx+1 : dy+1;
49 | }
50 | }
51 | return v;
52 | }
53 | ```
54 |
--------------------------------------------------------------------------------
/programming/checkpoints/reverse-linked-list.md:
--------------------------------------------------------------------------------
1 | # Reverse Linked List
2 |
3 | https://www.interviewbit.com/problems/reverse-linked-list/
4 |
5 | Reverse a linked list. Do it in-place and in one-pass.
6 |
7 | For example:
8 |
9 | Given 1->2->3->4->5->NULL,
10 |
11 | return 5->4->3->2->1->NULL.
12 |
13 | ## Solution
14 |
15 | ### Editorial
16 | ```cpp
17 | ListNode *Solution::reverseList(ListNode *head) {
18 | if (head == NULL) return head;
19 | ListNode *cur = head, *nextNode, *prevNode;
20 | prevNode = NULL;
21 |
22 | while (cur != NULL) {
23 | nextNode = cur->next;
24 | cur->next = prevNode;
25 | prevNode = cur;
26 | cur = nextNode;
27 | }
28 |
29 | head = prevNode;
30 | return head;
31 | }
32 |
33 | ```
34 |
35 | ### Mine
36 | ```cpp
37 | ListNode* RecursiveReverse(ListNode* curr, ListNode* next, ListNode* prev){
38 | if (!curr)
39 | return prev;
40 | next = curr->next;
41 | curr->next = prev;
42 | RecursiveReverse(next, next, curr);
43 | }
44 |
45 | ListNode* Solution::reverseList(ListNode* A) {
46 | return RecursiveReverse(A, A->next, NULL);
47 | }
48 | ```
49 |
50 |
--------------------------------------------------------------------------------
/programming/checkpoints/subtract.md:
--------------------------------------------------------------------------------
1 | # SUBTRACT
2 |
3 | https://www.interviewbit.com/problems/subtract/
4 |
5 | Given a singly linked list, modify the value of first half nodes such that :
6 |
7 | 1. 1st node's new value = the last node's value - first node's current value
8 | 2. 2nd node's new value = the second last node's value - 2nd node's current value,
9 |
10 | and so on ...
11 |
12 | ### NOTE
13 |
14 | If the length L of linked list is odd, then the first half implies at first floor(L/2) nodes. So, if L = 5, the first half refers to first 2 nodes.
15 | If the length L of linked list is even, then the first half implies at first L/2 nodes. So, if L = 4, the first half refers to first 2 nodes.
16 |
17 |
18 | Example :
19 |
20 | Given linked list 1 -> 2 -> 3 -> 4 -> 5,
21 |
22 | You should return 4 -> 2 -> 3 -> 4 -> 5
23 | as
24 | ```
25 | for first node, 5 - 1 = 4
26 | for second node, 4 - 2 = 2
27 | ```
28 | Try to solve the problem using constant extra space.
29 |
30 | ## Solution
31 |
32 | ```cpp
33 | ListNode *revert(ListNode *start) {
34 | if (!start)
35 | return NULL;
36 |
37 | ListNode *n1 = start;
38 | ListNode *n2 = n1->next;
39 | ListNode *n3;
40 |
41 | while (n2) {
42 | n3 = n2->next;
43 | n2->next = n1;
44 | n1 = n2;
45 | n2 = n3;
46 | }
47 | start->next = NULL;
48 |
49 | return n1;
50 | }
51 |
52 | ListNode *Solution::subtract(ListNode *A) {
53 | if (!A)
54 | return NULL;
55 | int len = 0;
56 |
57 | for (ListNode *n = A; n; n = n->next)
58 | len++;
59 | if (len < 2)
60 | return A;
61 |
62 | int halfLen = len / 2 + len % 2;
63 | ListNode *A2 = A;
64 | for (int i = 0; i < halfLen; i++)
65 | A2 = A2->next;
66 |
67 | ListNode *rear = revert(A2);
68 | ListNode *tf = A, *tr = rear;
69 | int halfLen2 = len / 2;
70 |
71 | for (int i = 0; i < halfLen2; i++) {
72 | tf->val = tr->val - tf->val;
73 | tf = tf->next;
74 | tr = tr->next;
75 | }
76 |
77 | revert(rear);
78 | return A;
79 | }
80 | ```
81 |
--------------------------------------------------------------------------------
/programming/checkpoints/unique-binary-search-trees.md:
--------------------------------------------------------------------------------
1 | # Unique Binary Search Trees
2 |
3 | https://www.interviewbit.com/problems/unique-binary-search-trees/
4 |
5 | Given A, generate all structurally unique BST's (binary search trees) that store values 1...A.
6 |
7 | ### Example
8 |
9 | Given A = 3, your program should return all 5 unique BST's shown below.
10 |
11 | ```
12 | 1 3 3 2 1
13 | \ / / / \ \
14 | 3 2 1 1 3 2
15 | / / \ \
16 | 2 1 2 3
17 | ```
18 |
19 |
20 | ## Solution
21 | ```cpp
22 | vector generate(int start, int end) {
23 | vector v;
24 |
25 | if (start > end) {
26 | v.push_back(NULL);
27 | return v;
28 | }
29 |
30 | if (start == end) {
31 | v.push_back(new TreeNode(start));
32 | return v;
33 | }
34 |
35 | for (auto i = start; i <= end; i++) {
36 | vector lft = generate(start, i - 1);
37 | vector rgt = generate(i + 1, end);
38 |
39 | for (auto l : lft) {
40 | for (auto r : rgt) {
41 | TreeNode *root = new TreeNode(i);
42 |
43 | root->left = l;
44 | root->right = r;
45 |
46 | v.push_back(root);
47 | }
48 | }
49 | }
50 | return v;
51 | }
52 |
53 | vector Solution::generateTrees(int n) {
54 |
55 | if (n == 0)
56 | return vector();
57 | else
58 | return generate(1, n);
59 | }
60 | ```
61 |
62 | ## Asked in
63 | * Amazon
64 | * Twitter
65 |
66 |
67 |
--------------------------------------------------------------------------------
/programming/code-ninja/build-identical-trees.md:
--------------------------------------------------------------------------------
1 | # Build Identical Trees
2 |
3 | https://www.interviewbit.com/problems/build-identical-trees/
4 |
5 | Given two binary trees T1 and T2, you have to find minimum number of insertions to be done in T1 to make it structurally identical to T2. Return -1 if not possible.
6 |
7 | ### Notes
8 |
9 | Assume insertions are done in a normal fashion in the BSTs.
10 | Assume while inserting, if the value of a node v is equal to value being inserted, we insert it in left subtree of node v.
11 | You can insert any positive or negative integer.
12 |
13 | ### Example
14 | ```
15 | Input 1:
16 |
17 | T1: 10
18 | / \
19 | 9 20
20 |
21 | T2: 5
22 | / \
23 | 2 7
24 | /
25 | 1
26 |
27 | If you insert 8 into T1, it will be structurally identical to T2. Hence answer is 1.
28 |
29 | Input 2:
30 |
31 | T1: 10
32 | / \
33 | 9 20
34 |
35 | T2: 5
36 | \
37 | 7
38 | ```
39 |
40 | You cannot make T1 and T2 structurally identical. Hence answer is -1.
41 |
42 | ## Solution
43 | ### Java
44 | ```java
45 | public class Solution {
46 | public int cntMatrixUtil(TreeNode A, TreeNode B, int min, int max) {
47 | int inserts = -1;
48 |
49 | if (A != null && B == null) {
50 | return inserts;
51 | }
52 | if (A != null && B != null) {
53 | inserts = 0;
54 |
55 | }
56 | if (A == null && B == null) {
57 | inserts = 0;
58 | return inserts;
59 | }
60 | if (A == null && B != null) {
61 |
62 | int mid = min + (max - min) / 2;
63 |
64 | A = new TreeNode(mid);
65 | inserts = 1;
66 | }
67 | int left = cntMatrixUtil(A.left, B.left, min, A.val);
68 | int right = cntMatrixUtil(A.right, B.right, A.val, max);
69 |
70 | if (left == -1 || right == -1) {
71 | return -1;
72 | }
73 | return inserts + cntMatrixUtil(A.left, B.left, min, A.val)
74 | + cntMatrixUtil(A.right, B.right, A.val, max);
75 | }
76 |
77 | public int cntMatrix(TreeNode A, TreeNode B) {
78 | return cntMatrixUtil(A, B, Integer.MIN_VALUE, Integer.MAX_VALUE);
79 | }
80 | }
81 |
82 | ```
83 |
--------------------------------------------------------------------------------
/programming/code-ninja/get-mode-array-updates.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/code-ninja/get-mode-array-updates.md
--------------------------------------------------------------------------------
/programming/dynamic-programming/best-time-to-buy-and-sell-stocks-i.md:
--------------------------------------------------------------------------------
1 | # Best Time To Buy and Sell Stocks I
2 |
3 | https://www.interviewbit.com/problems/best-time-to-buy-and-sell-stocks-i
4 |
5 |
6 |
7 | ## Hint1
8 |
9 | Basically you need to find the maximum value of A[j]-A[i] where j>i.
10 |
11 | Now can you do this?
12 |
13 | ## Hint 2
14 |
15 | If you buy your stock on day i, you'd obviously want to sell it on the day its price is maximum after that day.
16 | So essentially at every index i, you need to find the maximum in the array in the suffix.
17 | Now this part can be done in 2 ways:
18 |
19 | 1) Have another array which stores that information.
20 | max[i] = max(max[i+1], A[i])
21 |
22 | 2) Start processing entries from the end maintaining a maximum till now. Constant additional space requirement.
23 |
24 | ## Solution
25 |
26 | ```cpp
27 |
28 | // editorial
29 |
30 | class Solution {
31 | public:
32 | int maxProfit(vector &prices) {
33 | int sz = prices.size();
34 | int maxTillNow = -1000000000, maxGain = 0;
35 | for (int i = sz - 1; i >= 0; i--) {
36 | maxGain = max(maxGain, maxTillNow - prices[i]);
37 | maxTillNow = max(maxTillNow, prices[i]);
38 | }
39 | return maxGain;
40 | }
41 | };
42 |
43 | // my
44 |
45 | int Solution::maxProfit(const vector &prices) {
46 | if(!prices.size())
47 | return 0;
48 | int res = 0, price = prices[0];
49 | for(int i = 1; i < prices.size(); i++){
50 | price = min(price, prices[i]);
51 | res = max(res, prices[i] - price);
52 | }
53 | return res;
54 | }
55 | ```
--------------------------------------------------------------------------------
/programming/dynamic-programming/best-time-to-buy-and-sell-stocks-ii.md:
--------------------------------------------------------------------------------
1 | # Best Time to Buy and Sell Stocks II
2 |
3 | https://www.interviewbit.com/problems/best-time-to-buy-and-sell-stocks-ii/
4 |
5 | Say you have an array for which the ith element is the price of a given stock on day i.
6 |
7 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
8 |
9 | Example :
10 | ```
11 | Input: [1 2 3]
12 | Return: 2
13 | ```
14 |
15 | ## Hint 1
16 |
17 | This problem can be solved in different ways.
18 |
19 | Try to observe when it will be optimal to buy and sell the stock.
20 |
21 | Or you can also try to come up with a dp solution such that what can be possible thing to do( states to go) after you purchase stock on some day.
22 |
23 | ## Hint 2
24 |
25 | Observation based solution:
26 |
27 | Note 1: I will never buy a stock and sell it in loss.
28 |
29 | Note 2: If A[i] < A[i+1], I will always buy a stock on i and sell it on i+1.
30 |
31 | Think and try to come up with a proof on the validity of the statement.
32 |
33 | DP based solution:
34 |
35 | Let Dp[i] = max profit you can gain in region (i,i+1,....,n).
36 |
37 | Then Dp[i] = max(Dp[i+1],-A[i] + max( A[j]+Dp[j] st j > i ) )
38 |
39 | Can you come up with base cases and direction of computation now?
40 |
41 |
42 | ## Solution
43 |
44 | ### Editorial
45 | ```cpp
46 | int Solution::maxProfit(const vector &prices) {
47 | int total = 0, sz = prices.size();
48 | for (int i = 0; i < sz - 1; i++) {
49 | if (prices[i+1] > prices[i]) total += prices[i+1] - prices[i];
50 | }
51 | return total;
52 | }
53 | ```
54 |
55 | ### Mine
56 | ```cpp
57 | int Solution::maxProfit(const vector &A) {
58 | vector temp(A.size(), 0);
59 | int buy = A[0], flag = 0, i = 1, max_sell = INT_MIN;
60 | int sol = 0;
61 | while(i < A.size()) {
62 | int diff = A[i] - A[i-1];
63 | if(diff > 0)
64 | sol = sol + diff;
65 | i++;
66 | }
67 | return sol;
68 | }
69 |
70 | ```
71 |
72 | ## Asked in
73 | * Amazon
74 | * Facebook
75 |
76 |
--------------------------------------------------------------------------------
/programming/dynamic-programming/shortest-common-superstring.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/dynamic-programming/shortest-common-superstring.md
--------------------------------------------------------------------------------
/programming/dynamic-programming/stairs.md:
--------------------------------------------------------------------------------
1 | # Stairs
2 |
3 | https://www.interviewbit.com/problems/stairs/
4 |
5 | You are climbing a stair case. It takes n steps to reach to the top.
6 |
7 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
8 |
9 | Example :
10 |
11 | ```
12 | Input : 3
13 | Return : 3
14 | Steps : [1 1 1], [1 2], [2 1]
15 | ```
16 |
17 | ## Solution
18 | ```cpp
19 | int Solution::climbStairs(int A) {
20 | if (A<2)
21 | return 1;
22 | vector dp(A+1);
23 | dp[0] = 1; // starting point, 1 way
24 | dp[1] = 1; // *_1_*
25 | dp[2] = 2; // *_1_*_1_* or *__2__*
26 | for (int i=3; i<=A; i++)
27 | dp[i] = dp[i-2] + dp[i-1];
28 | return dp[A];
29 | }
30 | ```
31 |
32 | ## Asked in
33 |
34 | * Morgan Stanley
35 | * Amazon
36 | * Intel
37 |
38 |
--------------------------------------------------------------------------------
/programming/dynamic-programming/unique-binary-search-trees-ii.md:
--------------------------------------------------------------------------------
1 | # Unique Binary Search Trees II
2 |
3 | https://www.interviewbit.com/problems/unique-binary-search-trees-ii/
4 |
5 | Given A, how many structurally unique BST's (binary search trees) that store values 1...A?
6 |
7 | Example :
8 |
9 | Given A = 3, there are a total of 5 unique BST's.
10 |
11 | ```
12 | 1 3 3 2 1
13 | \ / / / \ \
14 | 3 2 1 1 3 2
15 | / / \ \
16 | 2 1 2 3
17 | ```
18 |
19 | ## Hint 1
20 |
21 | Can you compute the answer for A = n if you know the answer for A = 1, A = 2, ... A = n-1 ?
22 |
23 | What values can you place at root first and how will it affect the answer? Try to think of DP.
24 |
25 | ## Solution Approach
26 |
27 | Lets say you know the answer for values i which ranges from 0 <= i <= n - 1.
28 |
29 | How do you calculate the answer for n.
30 |
31 | Lets consider the number [1, n]
32 |
33 | We have n options of choosing the root.
34 |
35 | If we choose the number j as the root, j - 1 numbers fall in the left subtree, n - j numbers fall in the right subtree. We already know how many ways there are to forming j - 1 trees using j - 1 numbers and n -j numbers.
36 |
37 | So we add number(j - 1) * number(n - j) to our solution.
38 |
39 | Can you use the above fact to construct a DP relation ?
40 |
41 | ## Solution
42 |
43 |
44 | ### Editorial
45 | ```cpp
46 | int Solution::numTrees(int n) {
47 | if (n == 0) return 1;
48 | if (n == 1) return 1;
49 |
50 | int result[n + 1];
51 | memset(result, 0, sizeof(result));
52 | result[0] = 1;
53 | result[1] = 1;
54 | if (n < 2) {
55 | return result[n];
56 | }
57 |
58 | for (int i = 2; i <= n; i++) {
59 | for (int k = 1; k <= i; k++) {
60 | result[i] = result[i] + result[k - 1] * result[i - k];
61 | }
62 | }
63 |
64 | return result[n];
65 | }
66 | ```
67 |
68 | ### Lightweight
69 | ```cpp
70 | int Solution::numTrees(int A) {
71 | int dp[A+1];
72 | dp[0] = 1;
73 | for(int i=1; i<=A;i++){
74 | dp[i] = 0;
75 | for(int j=1; j<=i; j++)
76 | dp[i] += dp[j-1]*dp[i-j];
77 | }
78 | return dp[A];
79 | }
80 | ```
81 |
82 | ## Asked in
83 |
--------------------------------------------------------------------------------
/programming/graph-data-structure-and-algorithms/convert-sorted-list-to-binary-search-tree.md:
--------------------------------------------------------------------------------
1 | # Convert Sorted List To Binary Search Tree
2 |
3 | https://www.interviewbit.com/problems/convert-sorted-list-to-binary-search-tree
4 |
5 |
6 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
7 |
8 | A height balanced BST : a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
9 |
10 | Example :
11 |
12 | Given A : 1 -> 2 -> 3
13 |
14 | A height balanced BST:
15 |
16 | ```
17 | 2
18 | / \
19 | 1 3
20 | ```
21 |
22 | ## Hint 1
23 |
24 | What will happen if you will make the middle element of linked list the root element of BST?
25 |
26 | ## Hint 2
27 |
28 | Bruteforce :
29 | Find the middle of the list, make it the root. Left part of the tree comes from the first half
30 | and right part of the tree comes from the later half.
31 |
32 | Can you think of making it better ?
33 | Note that you can construct the left tree first by passing the size of the left tree that you expect.
34 |
35 | ## Solution
36 |
37 | ```cpp
38 |
39 | /////////////////////////////////
40 |
41 | TreeNode *makeTree(ListNode *&head, int start, int end) {
42 | if (start > end)
43 | return 0;
44 | int mid = start + (end - start) / 2;
45 | TreeNode *left = makeTree(head, start, mid - 1);
46 | TreeNode *root = new TreeNode(head->val);
47 | head = head->next;
48 | TreeNode *right = makeTree(head, mid + 1, end);
49 | root->left = left;
50 | root->right = right;
51 | return root;
52 | }
53 |
54 | TreeNode *Solution::sortedListToBST(ListNode *A) {
55 | if (!A)
56 | return 0;
57 | int len = 0;
58 | for (ListNode *curr = A; curr; curr = curr->next)
59 | len++;
60 | return makeTree(A, 0, len - 1);
61 | }
62 |
63 | /////////////////////////////////
64 | ```
--------------------------------------------------------------------------------
/programming/greedy-algorithm/highest-product.md:
--------------------------------------------------------------------------------
1 | # Highest Product
2 |
3 | https://www.interviewbit.com/problems/highest-product
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | #if 1 // O(n log n)
10 |
11 | int Solution::maxp3(vector &A) {
12 | auto n = A.size();
13 | sort(A.begin(), A.end());
14 | int allPositives = A[n-1] * A[n-2] * A[n-3];
15 | int twoNegatives = A[n-1] * A[0] * A[1];
16 | return max(allPositives, twoNegatives);
17 | }
18 |
19 | #else // O(n)
20 |
21 | int Solution::maxp3(vector &A) {
22 | int a, b, c, z, y;
23 | a = b = c = INT_MIN;
24 | z = y = INT_MAX;
25 |
26 | for (auto k : A) {
27 | if (k > a)
28 | c = b, b = a, a = k;
29 | else if (k > b)
30 | c = b, b = k;
31 | else if (k > c)
32 | c = k;
33 |
34 | if (k < z)
35 | y = z, z = k;
36 | else if (k < y)
37 | y = k;
38 | }
39 | //cout << a << " " << b << " " << c << " " << z << " " << y << " " << endl;
40 |
41 | return max(a * b * c, a * z * y);
42 | }
43 | #endif
44 | ```
--------------------------------------------------------------------------------
/programming/hashing/2-sum.md:
--------------------------------------------------------------------------------
1 | # 2 Sum
2 |
3 | https://www.interviewbit.com/problems/2-sum
4 |
5 |
6 |
7 | ## Hint 1
8 |
9 | O(n^2) runtime, O(1) space - Brute force:
10 |
11 | The brute force approach is simple. Loop through each element x and find if there is another value that equals to target - x. As finding another value requires looping through the rest of array, its runtime complexity is O(n^2).
12 |
13 | To improve on it, notice that when we fix one of the integers 'curValue', we know the value of the other integer we need to find ( target - curValue ).
14 | Then it becomes a simple search problem. You can store all the integers of the array in a hashmap and do a lookup to check if the elements exists in the map.
15 |
16 | ## Hint 2
17 |
18 | Have you checked cases where the element you are looking up in the map is same as the curValue.
19 |
20 | For example, consider the following cases :
21 |
22 | A:[4 4] target: 8
23 | and A :[3 4] target: 8
24 |
25 | The answer in first case should be [1 2] and in second case, it should be empty.
26 |
27 |
28 | ## Solution
29 |
30 | ```cpp
31 |
32 | vector Solution::twoSum(const vector &A, int target) {
33 | unordered_map m;
34 | for (int i = 0; i < A.size(); i++) {
35 | int comp = target - A[i];
36 |
37 | if (m.find(comp) != m.end())
38 | return { m[comp] + 1, i + 1 };
39 |
40 | if (m.find(A[i]) == m.end())
41 | m[A[i]] = i;
42 | }
43 | return {};
44 | }
45 |
46 | // fastest
47 |
48 | vector Solution::twoSum(const vector &A, int B) {
49 | int n = A.size();
50 | vector v;
51 | if (n < 2) {
52 | return v;
53 | }
54 | unordered_map seen;
55 | seen.reserve(A.size());
56 | for (int i = 0; i < A.size(); ++i) {
57 | long long target = B - A[i];
58 | if (target < INT_MIN || target > INT_MAX) continue;
59 | auto it = seen.find(target);
60 | if (it != seen.end())
61 | return vector{ it->second + 1, i + 1 };
62 | seen.insert(make_pair(A[i], i));
63 | }
64 | return vector{};
65 | }
66 | ```
--------------------------------------------------------------------------------
/programming/hashing/anagrams.md:
--------------------------------------------------------------------------------
1 | # Anagrams
2 |
3 | https://www.interviewbit.com/problems/anagrams
4 |
5 |
6 |
7 | ## Hint 1
8 |
9 | Anagrams will map to the same string if the characters in the string are sorted.
10 | Can you use the above fact to come up with a strategy ?
11 |
12 | ## Hint 2
13 |
14 | Anagrams will map to the same string if the characters in the string are sorted.
15 | We can maintain a hashmap with the key being the sorted string and the value being
16 | the list of strings ( which have the sorted characters as key ).
17 |
18 | ## Solution
19 |
20 | ```cpp
21 |
22 | // iterator
23 |
24 | vector > Solution::anagrams(const vector &A) {
25 | vector> res;
26 | unordered_map m;
27 | for (int i=0; i());
35 | }
36 | res[(*it).second].push_back(i + 1);
37 | }
38 | return res;
39 | }
40 |
41 | // my
42 |
43 | vector> Solution::anagrams(const vector &A) {
44 | vector> res;
45 | unordered_map m;
46 | for (int i = 0; i < A.size(); i++) {
47 | string s = A[i];
48 | sort(s.begin(), s.end());
49 | if (!m.count(s)) {
50 | m[s] = res.size();
51 | res.push_back(vector());
52 | }
53 | res[m[s]].push_back(i + 1);
54 | }
55 | return res;
56 | }
57 |
58 | // my
59 |
60 | vector> Solution::anagrams(const vector &A) {
61 | map> m;
62 | for (int i = 0; i < A.size(); i++) {
63 | string s = A[i];
64 | sort(s.begin(), s.end());
65 | m[s].push_back(i + 1);
66 | }
67 | vector> res;
68 | for (auto x : m)
69 | res.push_back(x.second);
70 |
71 | return res;
72 | }
73 | ```
--------------------------------------------------------------------------------
/programming/hashing/colorful-number.md:
--------------------------------------------------------------------------------
1 | # Colorful Number
2 |
3 | https://www.interviewbit.com/problems/colorful-number
4 |
5 | For Given Number N find if its COLORFUL number or not
6 |
7 | Return 0/1
8 |
9 | COLORFUL number:
10 |
11 | A number can be broken into different contiguous sub-subsequence parts.
12 | Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245.
13 | And this number is a COLORFUL number, since product of every digit of a contiguous subsequence is different
14 | Example:
15 |
16 | ```
17 | N = 23
18 | 2 3 23
19 | 2 -> 2
20 | 3 -> 3
21 | 23 -> 6
22 | ```
23 |
24 | this number is a COLORFUL number since product of every digit of a sub-sequence are different.
25 |
26 | Output : 1
27 |
28 | ## Hint 1
29 |
30 | Note that input number can be of length atmax 10.
31 |
32 | So, number of substring can be atmax 45.
33 |
34 | ## Solution Approach
35 |
36 | It is one of the easiest problem in this section.
37 | You just need to simulate what has been stated in the problem.
38 | Iterate over all substrings of number, and then check if the number resulting from the multiplication has been stored by us or not using hashing.
39 |
40 | Example:
41 | ```
42 | N = 123
43 | 1 2 3 12 23 123
44 | 1 -> 1
45 | 2 -> 2
46 | 3 -> 3
47 | 12 -> 2 uh-oh, we have already encountered 2 before. Return 0
48 | ```
49 |
50 | ## Solution
51 |
52 | ```cpp
53 |
54 |
55 | int Solution::colorful(int A) {
56 | vector vec;
57 | while (A) {
58 | vec.push_back(A % 10);
59 | A /= 10;
60 | }
61 | reverse(vec.begin(), vec.end());
62 | unordered_map hash;
63 | for (auto i = 0; i < vec.size(); ++i) {
64 | long long value = 1;
65 | for (auto j = i; j < vec.size(); ++j) {
66 | value *= vec[j];
67 | if (hash.find(value) != hash.end())
68 | return 0;
69 | hash.insert({value, true});
70 | }
71 | }
72 | return 1;
73 | }
74 |
75 | ```
--------------------------------------------------------------------------------
/programming/hashing/diffk-ii.md:
--------------------------------------------------------------------------------
1 | # Diffk II
2 |
3 | https://www.interviewbit.com/problems/diffk-ii
4 |
5 |
6 | ## Hint 1
7 |
8 | The naive approach obviously is exloring all combinations of 2 integers using 2 loops and then check their difference.
9 |
10 | However, lets look at it like this.
11 | We are looking to find pair of integers where A[i] - A[j] = k, k being known entity
12 | Lets say we lock A[i] ( i.e. we know A[i]), do we know what A[j] should be ?
13 | Once we know what A[j] we want, does it reduce to a search / lookup problem ?
14 |
15 | Solution approach
16 |
17 | We are looking to find pair of integers where A[i] - A[j] = k, k being known entity
18 | Lets say we lock A[i] ( i.e. we know A[i]), do we know what A[j] should be ?
19 | A[j] = A[i] - k.
20 |
21 | We can store all the numbers in a hashmap / hashset and then lookup A[j] in it to find out if A[j] exists.
22 |
23 | Corner case: How do you handle case when k = 0 cleanly ?
24 |
25 |
26 | ## Solution
27 |
28 | ```cpp
29 |
30 |
31 | // fastest
32 |
33 | int Solution::diffPossible(const vector &A, int k) {
34 | unordered_set s;
35 | for (auto x:A) {
36 | if(s.count(x-k) || s.count(x+k))
37 | return true;
38 | s.insert(x);
39 | }
40 | return false;
41 | }
42 |
43 | // misc
44 |
45 | int Solution::diffPossible(const vector &A, int B) {
46 | vector input(A);
47 | sort(input.begin(), input.end());
48 | auto p = 0, q = 0;
49 | auto size = input.size();
50 | while (q < size)
51 | {
52 | if (p == q)
53 | ++q;
54 | else if (input[q]-input[p] == B && p!=q)
55 | return 1;
56 | else if (input[q]-input[p] < B)
57 | ++q;
58 | else if (input[q]-input[p] > B)
59 | ++p;
60 | }
61 | return 0;
62 | }
63 | ```
--------------------------------------------------------------------------------
/programming/hashing/fraction.md:
--------------------------------------------------------------------------------
1 | # Fraction
2 |
3 | https://www.interviewbit.com/problems/fraction
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | string Solution::fractionToDecimal(int numerator, int denominator) {
10 |
11 | int64_t n = numerator, d = denominator;
12 | if (n == 0) return "0";
13 | string res;
14 | if (n < 0 ^ d < 0) res += '-';
15 | n = abs(n), d = abs(d);
16 | res += to_string((n / d));
17 | if (n % d == 0) return res;
18 | res += '.';
19 |
20 | unordered_map map;
21 | for (int64_t r = n % d; r; r %= d) {
22 | if (map.find(r) != map.end()) {
23 | res.insert(map[r], 1, '(');
24 | res += ')';
25 | break;
26 | }
27 | map[r] = res.size();
28 | r *= 10;
29 | res.push_back((char)('0' + (r / d)));
30 | }
31 |
32 | return res;
33 | }
34 | ```
--------------------------------------------------------------------------------
/programming/hashing/valid-sudoku.md:
--------------------------------------------------------------------------------
1 | # Valid Sudoku
2 |
3 | https://www.interviewbit.com/problems/valid-sudoku
4 |
5 |
6 |
7 | Very simple simulation problem. Just need to keep track of the digits seen in every row,
8 | every column and every block as defined in the rules.
9 | Whenever you encounter a digit already seen, you know the sudoku is not valid.
10 |
11 | Note that this problem will get very complicated if you were to determine if the sudoku was solvable.
12 |
13 |
14 |
15 | ## Solution
16 |
17 | ```cpp
18 |
19 | #define GRIDSIZE 9
20 |
21 | bool isValid(const vector &A, int row, int col) {
22 | char elem = A[row][col];
23 |
24 | //check range
25 | if (elem - '0' < 1 || elem - '0' > 9)
26 | return false;
27 |
28 | //check for duplicates in row and col
29 | for (auto p = 0; p < GRIDSIZE; ++p) {
30 | if (A[p][col] == elem && p != row) return false;
31 | if (A[row][p] == elem && p != col) return false;
32 | }
33 |
34 | //check for duplicates in subgrids
35 | int subRow = (row / 3) * 3;
36 | int subCol = (col / 3) * 3;
37 |
38 | for (auto i = subRow; i < subRow + 3; ++i) {
39 | for (auto j = subCol; j < subCol + 3; ++j)
40 | if (A[i][j] == elem && (i != row || j != col))
41 | return false;
42 | }
43 |
44 | return 1;
45 | }
46 |
47 | int sudokuRunner(const vector &A, int row, int col) {
48 | if (row == 9)
49 | return 1;
50 |
51 | int nextRow, nextCol;
52 | if (col == 8) {
53 | nextRow = row + 1;
54 | nextCol = 0;
55 | } else {
56 | nextRow = row;
57 | nextCol = col + 1;
58 | }
59 |
60 | if (A[row][col] != '.') {
61 | if (!isValid(A, row, col))
62 | return 0;
63 | }
64 |
65 | return sudokuRunner(A, nextRow, nextCol);
66 | }
67 |
68 | int Solution::isValidSudoku(const vector &A) {
69 | if (A.size() != GRIDSIZE || A[0].size() != GRIDSIZE)
70 | return 0;
71 | return sudokuRunner(A, 0, 0);
72 | }
73 | ```
--------------------------------------------------------------------------------
/programming/heaps-and-maps/distinct-numbers-in-window.md:
--------------------------------------------------------------------------------
1 | # Distinct Numbers In Window
2 |
3 | https://www.interviewbit.com/problems/distinct-numbers-in-window
4 |
5 |
6 | If you have solution for window [i, i+k-1], can you quickly build solution for window [i+1, i+k], using some data structure?
7 |
8 | What could be this data structure? A data structure which can store distinct elements(and their count?)?
9 |
10 |
11 |
12 | If you have solution for window [i, i+k-1], can you quickly build solution for window [i+1, i+k]?
13 |
14 | If we have a data structure where we can maintain count of all keys and number of distinct keys, then we just have to reduce count of key A[i] and increasing count of A[i+k]. If count of some key has been reduced to zero, we need to remove that key.
15 |
16 | This structure is a hashmap. All operations that we have said a constant time in it.
17 |
18 | ## Solution
19 |
20 | ```cpp
21 |
22 | // editorial
23 |
24 | vector Solution::dNums(vector &A, int B) {
25 | assert(B <= A.size());
26 | int n = A.size();
27 | vector ret;
28 | unordered_map m;
29 | for (int i = 0; i < n; i++) {
30 | m[A[i]]++;
31 | if (i - B + 1 >= 0) {
32 | ret.push_back(m.size());
33 | m[A[i - B + 1]]--;
34 | if (m[A[i - B + 1]] == 0)
35 | m.erase(A[i - B + 1]);
36 | }
37 | }
38 | return ret;
39 | }
40 |
41 | vector Solution::dNums(vector &A, int B) {
42 |
43 | vector ans;
44 |
45 | if (B > A.size()) {
46 | return ans;
47 | }
48 |
49 | map m;
50 | int unique = 0;
51 |
52 | for (int i = 0; i < B; i++) {
53 | auto it = m.find(A[i]);
54 | if (it == m.end()) {
55 | m[A[i]] = 1;
56 | unique++;
57 | } else {
58 | it->second++;
59 | }
60 | }
61 |
62 | ans.push_back(unique);
63 |
64 | for (int i = B; i < A.size(); i++) {
65 | auto it = m.find(A[i - B]);
66 | if (it->second == 1) {
67 | m.erase(it);
68 | unique--;
69 | } else {
70 | it->second--;
71 | }
72 | auto temp = m.find(A[i]);
73 | if (temp != m.end()) {
74 | temp->second++;
75 | } else {
76 | m[A[i]] = 1;
77 | unique++;
78 | }
79 | ans.push_back(unique);
80 | }
81 |
82 | return ans;
83 | }
84 | ```
--------------------------------------------------------------------------------
/programming/heaps-and-maps/magician-and-chocolates.md:
--------------------------------------------------------------------------------
1 | # Magician and Chocolates
2 |
3 | https://www.interviewbit.com/problems/magician-and-chocolates
4 |
5 |
6 |
7 | Given N bags, each bag contains Ai chocolates. There is a kid and a magician.
8 | In one unit of time, kid chooses a random bag i, eats Ai chocolates,
9 | then the magician fills the ith bag with floor(Ai/2) chocolates.
10 |
11 | Given Ai for 1 <= i <= N, find the maximum number of chocolates kid can eat in K units of time.
12 |
13 |
14 |
15 | It is quite trivial to figure out that the kid will always choose the bag with the maximum number of chocolates.
16 | By knowing this fact, how would you solve the problem ?
17 |
18 | The solution to this problem can be found greedily. At any time t, the kid will always choose the bag with the maximum number of chocolates and consume all it's chocolates.
19 | So we need to maintain the current maximum size among all bags for every time t = 1, ... , K and also updating the sizes of the bags.
20 | This can be done using a max heap: https://en.wikipedia.org/wiki/Min-max_heap
21 |
22 | ## Solution
23 |
24 | ```cpp
25 |
26 | // editorial
27 |
28 | long long int mod = 1000000007;
29 | int Solution::nchoc(int A, vector &B) {
30 | int N = B.size();
31 | int K = A;
32 | long long int ans = 0;
33 | priority_queue heap(B.begin(),B.end());
34 | while(K--){
35 | long long int max_elem = heap.top();
36 | ans += max_elem;
37 | ans = ans % mod;
38 | heap.pop();
39 | heap.push((int)(max_elem/2));
40 | }
41 | return ans;
42 | }
43 |
44 |
45 | ```
--------------------------------------------------------------------------------
/programming/linked-lists/add-two-numbers-as-lists.md:
--------------------------------------------------------------------------------
1 | # Add Two Numbers As Lists
2 |
3 | https://www.interviewbit.com/problems/add-two-numbers-as-lists
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | ListNode* Solution::addTwoNumbers(ListNode* a, ListNode* b) {
10 | int carry = 0;
11 | ListNode * head = 0, * prev;
12 | while (a || b || carry) {
13 | int sum = (a ? a->val : 0) + (b ? b->val : 0) + carry;
14 | ListNode * node = new ListNode(sum % 10);
15 | carry = sum / 10;
16 |
17 | if (!head)
18 | head = prev = node;
19 | else {
20 | prev->next = node;
21 | prev = prev->next;
22 | }
23 |
24 | if (a)
25 | a = a->next;
26 | if (b)
27 | b = b->next;
28 | }
29 | return head;
30 | }
31 |
32 | ```
--------------------------------------------------------------------------------
/programming/linked-lists/insertion-sort-list.md:
--------------------------------------------------------------------------------
1 | # Insertion Sort List
2 |
3 | https://www.interviewbit.com/problems/insertion-sort-list
4 |
5 |
6 |
7 | ## Hint 1
8 |
9 | If you know about the insertion sort, then the key step here is swapping two adjacent nodes.
10 |
11 | ## Hint 2
12 |
13 | This is very much a simulation problem.
14 |
15 | The only trick is how do you move a node from ith position to jth position.
16 | How do you move the pointers to do so ? Would having a temporary node help ?
17 |
18 |
19 | ## Solution
20 |
21 | ```cpp
22 |
23 | ListNode *Solution::insertionSortList(ListNode *head) {
24 | if (!head || !head->next)
25 | return head;
26 | ListNode *sorted = 0;
27 |
28 | while (head) {
29 | ListNode *curr = head;
30 | head = head->next;
31 |
32 | if (!sorted || sorted->val >= curr->val) {
33 | curr->next = sorted;
34 | sorted = curr;
35 | } else {
36 | ListNode *temp = sorted;
37 | while (temp) {
38 | ListNode *s = temp;
39 | temp = temp->next;
40 |
41 | if (!s->next || s->next->val > curr->val) {
42 | curr->next = s->next;
43 | s->next = curr;
44 | break;
45 | }
46 | }
47 | }
48 | }
49 | return sorted;
50 | }
51 | ```
--------------------------------------------------------------------------------
/programming/linked-lists/k-reverse-linked-list.md:
--------------------------------------------------------------------------------
1 | # K Reverse Linked List
2 |
3 | https://www.interviewbit.com/problems/k-reverse-linked-list
4 |
5 |
6 |
7 | Given a singly linked list and an integer K, reverses the nodes of the
8 |
9 | list K at a time and returns modified linked list.
10 |
11 | ## Hint 1
12 | Try to split the list into buckets of K.
13 |
14 | Solution approach
15 | Split the list into buckets of length K and then reverse each of them.
16 | After this you have to concatenate the buckets and return the list. To split the list into buckets of length K,
17 | use 2 pointers that are K elements afar. To reverse a linked list check this.
18 |
19 | ## Solution
20 |
21 | ```cpp
22 |
23 | // fastest
24 |
25 | ListNode *Solution::reverseList(ListNode *A, int B) {
26 |
27 | struct ListNode *current = A;
28 | struct ListNode *next = NULL;
29 | struct ListNode *prev = NULL;
30 | int count = 0;
31 |
32 | /*reverse first k nodes of the linked list */
33 | while (count < B) {
34 | next = current->next;
35 | current->next = prev;
36 | prev = current;
37 | current = next;
38 | count++;
39 | }
40 | if (next != NULL)
41 | A->next = reverseList(next, B);
42 | return prev;
43 | }
44 |
45 | // mine
46 |
47 | ListNode *Solution::reverseList(ListNode *head, int k) {
48 | if (k == 1)
49 | return head;
50 |
51 | ListNode *next = 0, *prev = 0, *curr = head;
52 |
53 | for (int i = 0; i < k && curr; i++) {
54 | next = curr->next;
55 | curr->next = prev;
56 | prev = curr;
57 | curr = next;
58 | }
59 |
60 | if (head)
61 | head->next = reverseList(curr, k);
62 |
63 | return prev;
64 | }
65 | ```
--------------------------------------------------------------------------------
/programming/linked-lists/remove-duplicates-from-sorted-list-ii.md:
--------------------------------------------------------------------------------
1 | # Remove Duplicates From Sorted List II
2 |
3 | https://www.interviewbit.com/problems/remove-duplicates-from-sorted-list-ii
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | ListNode *Solution::deleteDuplicates(ListNode *A) {
10 | ListNode *head = A, *curr = A, *prev = 0;
11 |
12 | ListNode tmp(0);
13 | tmp.next = head;
14 | prev = &tmp;
15 |
16 | while (curr) {
17 | while (curr->next && curr->val == curr->next->val)
18 | curr = curr->next;
19 |
20 | if (prev->next == curr)
21 | prev = prev->next;
22 | else
23 | prev->next = curr->next;
24 |
25 | curr = curr->next;
26 | }
27 |
28 | return tmp.next;
29 | }
30 | ```
--------------------------------------------------------------------------------
/programming/linked-lists/remove-duplicates-from-sorted-list.md:
--------------------------------------------------------------------------------
1 | # Remove Duplicates
2 |
3 | https://www.interviewbit.com/problems/remove-duplicates-from-sorted-list
4 |
5 |
6 | Given a sorted linked list, delete all duplicates such that each element appear only once.
7 |
8 | For example,
9 |
10 | Given 1->1->2, return 1->2.
11 |
12 | Given 1->1->2->3->3, return 1->2->3.
13 |
14 | ## Hint 1
15 |
16 | You need to change next pointer of some element to next different element. Take care of corner cases if any.
17 |
18 | ## Solution Approach
19 |
20 | Skip the node where head->next != NULL && head->val == head->next->val.
21 |
22 | Make sure you take care of corner cases :
23 |
24 | 1. Do you handle repetitions at the end ? ex : 1 -> 1
25 | 2. Do you handle cases where there is just one element ? ex : 1
26 | 3. Do you handle cases where there is just one element repeated numerous times ? 1->1->1->1->1->1
27 |
28 |
29 | ## Solution
30 |
31 | ```cpp
32 |
33 | *
34 | * Definition for singly-linked list.
35 | * struct ListNode {
36 | * int val;
37 | * ListNode *next;
38 | * ListNode(int x): val(x), next(NULL) {}
39 | * };
40 | */
41 |
42 | /* editorial */
43 |
44 | ListNode *deleteDuplicates(ListNode *head) {
45 | ListNode *origin = head;
46 | while (head != NULL) {
47 | while (head->next != NULL && head->val == head->next->val) {
48 | head->next = head->next->next;
49 | }
50 | head = head->next;
51 | }
52 | return origin;
53 | }
54 |
55 | /* mine */
56 |
57 | ListNode *Solution::deleteDuplicates(ListNode *A) {
58 | ListNode *head = A;
59 | while (A) {
60 | if (A->next && A->next->val == A->val) {
61 | A->next = A->next->next;
62 | } else {
63 | A = A->next;
64 | }
65 | }
66 | return head;
67 | }
68 | ```
--------------------------------------------------------------------------------
/programming/linked-lists/remove-nth-element.md:
--------------------------------------------------------------------------------
1 | # Remove Nth Element
2 |
3 | https://www.interviewbit.com/problems/remove-nth-element
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | ListNode* Solution::removeNthFromEnd(ListNode* A, int B) {
10 | ListNode *head = A, *a, *b, *prev = 0;
11 |
12 | for (a = head; a && B; a = a->next) {
13 | B--;
14 | }
15 |
16 | for (b = head; a && b; a = a->next) {
17 | prev = b;
18 | b = b->next;
19 | }
20 |
21 | if (prev && b) {
22 | prev->next = b->next;
23 | } else {
24 | head = head->next;
25 | }
26 |
27 | return head;
28 | }
29 |
30 | ```
--------------------------------------------------------------------------------
/programming/linked-lists/remove-nth-node-from-list-end.md:
--------------------------------------------------------------------------------
1 | # Remove Nth Node from List End
2 | https://www.interviewbit.com/problems/remove-nth-node-from-list-end/
3 |
4 | Given a linked list, remove the nth node from the end of list and return its head.
5 |
6 | For example,
7 |
8 | Given linked list: 1->2->3->4->5, and n = 2.
9 |
10 | After removing the second node from the end, the linked list becomes 1->2->3->5.
11 |
12 | Note:
13 |
14 | If n is greater than the size of the list, remove the first node of the list.
15 | Try doing it using constant additional space.
16 |
17 | ## Hint 1
18 |
19 | Can you remove xth node from start instead of nth node from end?
20 | Can you figure out the position of node from start given its position from end?
21 |
22 | ## Solution Approach
23 |
24 | Obviously, since we do not have back pointers, reaching the end node and then making our way back is not an option.
25 |
26 | There are 2 approaches :
27 |
28 | 1) Find out the length of the list in one go. Then you know the number of node to be removed. Traverse to the node and remove it.
29 |
30 | 2) Make the first pointer go n nodes. Then move the second and first pointer simultaneously. This way, the first pointer is always ahead of the second pointer by n nodes. So when first pointer reaches the end, you are on the node to be removed.
31 |
32 | ## Solution
33 |
34 | ```cpp
35 | ListNode* Solution::removeNthFromEnd(ListNode* A, int B) {
36 | ListNode *head = A, *a, *b, *prev = 0;
37 |
38 | for (a = head; a && B; a = a->next) {
39 | B--;
40 | }
41 |
42 | for (b = head; a && b; a = a->next) {
43 | prev = b;
44 | b = b->next;
45 | }
46 |
47 | if (prev && b) {
48 | prev->next = b->next;
49 | } else {
50 | head = head->next;
51 | }
52 |
53 | return head;
54 | }
55 | ```
56 |
57 | ## Asked in
58 |
59 | * HCL
60 | * Amazon
61 |
--------------------------------------------------------------------------------
/programming/linked-lists/swap-list-nodes-in-pairs.md:
--------------------------------------------------------------------------------
1 | # Swap List Nodes in pairs
2 |
3 | https://www.interviewbit.com/problems/swap-list-nodes-in-pairs/
4 |
5 | Given a linked list, swap every two adjacent nodes and return its head.
6 |
7 | For example,
8 |
9 | Given 1->2->3->4, you should return the list as 2->1->4->3.
10 |
11 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
12 |
13 | ## Hint 1
14 |
15 | A->B->C.
16 |
17 | Take a look at A,B. How can you change the next pointer of these elements without changing their values such that they are swapped?
18 |
19 | ## Solution Approach
20 |
21 | Lets first look at the problem of swapping 2 nodes.
22 |
23 | Method 1: Just swap the values in the 2 nodes. In most cases, this won't be a permissible solution.
24 |
25 | Method 2: Move around the pointers.
26 |
27 | ## Solution
28 |
29 | ```cpp
30 | ListNode* Solution::swapPairs(ListNode* A) {
31 | if (!A)
32 | return NULL;
33 | ListNode * head = A, * curr = A, * next = A->next, * prev = 0;
34 | if (next)
35 | A = next;
36 | while (next) {
37 | curr->next = next->next;
38 | next->next = curr;
39 | if(prev)
40 | prev->next = next;
41 | prev = curr;
42 | curr = curr->next;
43 | if(curr)
44 | next = curr->next;
45 | else
46 | next = 0;
47 | }
48 | return A;
49 | }
50 | ```
51 |
52 | ## Asked in
53 |
54 | * Microsoft
55 | * Amazon
56 |
57 |
--------------------------------------------------------------------------------
/programming/math/all-factors.md:
--------------------------------------------------------------------------------
1 | # All Factors
2 |
3 | https://www.interviewbit.com/problems/all-factors
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | vector Solution::allFactors(int A) {
10 | vector factors;
11 | int sqrtA = int(sqrt(A));
12 | for (int i=1; i<=sqrtA; i++) {
13 | if (A % i==0) {
14 | factors.push_back(i);
15 | if (i!=sqrtA) {
16 | factors.push_back(A/i);
17 | }
18 | }
19 | }
20 | sort(factors.begin(), factors.end());
21 | return factors;
22 | }
23 | ```
--------------------------------------------------------------------------------
/programming/math/city-tour.md:
--------------------------------------------------------------------------------
1 | # City Tour
2 |
3 | https://www.interviewbit.com/problems/city-tour
4 |
5 |
6 | According to the constraints, we can solve this problem in O(N ^ 2).
7 |
8 | First, find all groups of consecutive unvisited cities and calculate the number
9 | of ways to combine them. Then for each group calculate the number of ways
10 | to visit all the cities of that group.
11 | ## Solution
12 |
13 | ```cpp
14 |
15 | #define ll long long
16 | #define MOD 1000000007
17 |
18 | ll powmod(ll base,ll exponent)
19 | {
20 | if(exponent<0) exponent+=MOD-1;
21 | ll ans=1;
22 | while(exponent){
23 | if(exponent&1)ans=(ans*base)%MOD;
24 | base=(base*base)%MOD;
25 | exponent/=2;
26 | }
27 | return ans;
28 | }
29 |
30 | int Solution::solve(int A, vector &B) {
31 | sort(B.begin(),B.end());
32 | long long fact[10000];
33 | fact[0] = 1;
34 | #define mod 1000000007
35 | for(int i = 1;i < 10000;i++){
36 | fact[i] = (fact[i-1]*i)%mod;
37 | }
38 | vector vs;
39 | long long n = B.size();
40 | vs.push_back(B[0]-1);
41 | for(int i = 1;i < n;i++){
42 | vs.push_back(B[i]-B[i-1]-1);
43 | }
44 | vs.push_back(A-B[n-1]);
45 | long long ans = 1;
46 | long long sum = 0,pro = 1;
47 | for(int i = 0;i < vs.size();i++){
48 | if(vs[i] == 0) continue;
49 | if(i != 0 && i != vs.size()-1) ans = (ans*powmod(2,vs[i]-1))%mod;
50 | sum = (sum + vs[i])%mod;
51 | pro = (pro*fact[vs[i]])%mod;
52 | }
53 | ans = (ans * fact[sum])%mod;
54 | ans = (ans * powmod(pro,mod-2))%mod;
55 | return ans;
56 | }
57 |
58 | ```
--------------------------------------------------------------------------------
/programming/math/excel-column-number.md:
--------------------------------------------------------------------------------
1 | # Excel Column Number
2 |
3 | https://www.interviewbit.com/problems/excel-column-number
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | int Solution::titleToNumber(string A) {
10 |
11 | int x = 0, p = 1;
12 | for (int i=A.length()-1; i>=0; i--) {
13 | x += int(A[i]-'A'+1) * p;
14 | p *= 26;
15 | }
16 |
17 | return x;
18 | }
19 |
20 | ```
--------------------------------------------------------------------------------
/programming/math/excel-column-title.md:
--------------------------------------------------------------------------------
1 | # Excel Column Title
2 |
3 | https://www.interviewbit.com/problems/excel-column-title
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 |
10 | string Solution::convertToTitle(int A) {
11 | string res;
12 | do {
13 | A--;
14 | res = char('A' + A % 26) + res;
15 | A /= 26;
16 | } while (A);
17 | return res;
18 | }
19 |
20 | /*
21 |
22 | string Solution::convertToTitle(int A) {
23 | string res;
24 | do {
25 | A--;
26 | res += A % 26 + 'A';
27 | A /= 26;
28 | } while (A);
29 | reverse(res.begin(), res.end());
30 | return res;
31 | }
32 | */
33 | ```
--------------------------------------------------------------------------------
/programming/math/fizzbuzz.md:
--------------------------------------------------------------------------------
1 | # Fizzbuzz
2 |
3 | https://www.interviewbit.com/problems/fizzbuzz
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | vector Solution::fizzBuzz(int A) {
10 | vector B;
11 | for (int i=1; i<=A; i++) {
12 | if (i%3==0 && i%5==0)
13 | B.push_back("FizzBuzz");
14 | else if (i%3==0)
15 | B.push_back("Fizz");
16 | else if (i%5==0)
17 | B.push_back("Buzz");
18 | else
19 | B.push_back(to_string(i));
20 | }
21 | return B;
22 | }
23 |
24 | /*
25 | vector Solution::fizzBuzz(int A) {
26 | vector B;
27 | for (int i=1; i<=A; i++)
28 | B.push_back(i%3==0 && i%5==0
29 | ? "FizzBuzz" : i%3==0
30 | ? "Fizz" : i%5==0
31 | ? "Buzz" : to_string(i));
32 | return B;
33 | }
34 | */
35 |
36 | /*
37 | vector Solution::fizzBuzz(int A) {
38 | vector B;
39 | for (int i=1; i<=A; i++) {
40 | string s;
41 | if (i%3==0) s+="Fizz";
42 | if (i%5==0) s+="Buzz";
43 | B.push_back(s.length() ? s : to_string(i));
44 | }
45 | return B;
46 | }
47 |
48 | */
49 | ```
--------------------------------------------------------------------------------
/programming/math/greatest-common-divisor.md:
--------------------------------------------------------------------------------
1 | # Greatest Common Divisor
2 |
3 | https://www.interviewbit.com/problems/greatest-common-divisor
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | int Solution::gcd(int A, int B) {
10 | if (B==0)
11 | return A;
12 | return gcd(B, A % B);
13 | }
14 |
15 | /*
16 | int Solution::gcd(int A, int B) {
17 | if(A 1 and A > 0. A and P both should be integers.
9 |
10 | Input: 4
11 | Output: True
12 | as 2^2 = 4.
13 | ## Solution
14 |
15 | ```cpp
16 |
17 | int Solution::isPower (int A) {
18 | if (A <= 1)
19 | return true;
20 |
21 | int sqrtA = floor(sqrt (A));
22 |
23 | if (sqrtA*sqrtA==A)
24 | return 1;
25 |
26 | for (int x = 2; x <= sqrtA; x++) {
27 | unsigned int p = x;
28 | while (p <= A) {
29 | p *= x;
30 | if (p == A)
31 | return 1;
32 | }
33 | }
34 |
35 | return 0;
36 | }
37 |
38 | /*
39 | int Solution::isPower (int A) {
40 | if (A <= 1)
41 | return 1;
42 | for (int i = 2; i Solution::primesum(int n) {
8 |
9 | vector isPrime(n+1, true);
10 | isPrime[0] = isPrime[1] = false;
11 |
12 | for (int p=2; p*p<=n; p++)
13 | if (isPrime[p])
14 | for (int i=p*p; i<=n; i+=p)
15 | isPrime[i] = false;
16 |
17 | vector B;
18 |
19 | for (int i=0; i &A) {
19 | int n = A.size();
20 |
21 | // First step: Increase all values by (arr[arr[i]]%n)*n
22 | for (int i=0; iINT_MAX || rINT_MAX || r=INT_MAX)
47 | return 0;
48 | return res * sign;
49 | }
50 | */
51 |
52 | /* // this one doesn't work
53 | int Solution::reverse(int A) {
54 | char digits[16];
55 | long long x = A<0 ? -A : A;
56 | int sign = A<0 ? -1 : 1;
57 | int n = 0;
58 | do {
59 | digits[n++] = x % 10;
60 | x /= 10;
61 | } while(x);
62 |
63 | long long res = 0;
64 | for (int p=1, i=n-1; i>=0; i--) {
65 | long long x = digits[i] * p;
66 | if (res + x >= INT_MAX)
67 | return 0;
68 | res += x;
69 | p *= 10;
70 | }
71 | return res * sign;
72 | }
73 | */
74 | ```
--------------------------------------------------------------------------------
/programming/math/sorted-permutation-rank.md:
--------------------------------------------------------------------------------
1 | # Sorted permutation rank
2 |
3 | https://www.interviewbit.com/problems/sorted-permutation-rank
4 |
5 | Given a string, find the rank of the string amongst its permutations sorted lexicographically.
6 | Assume that no characters are repeated.
7 |
8 | Example :
9 |
10 | Input : 'acb'
11 | Output : 2
12 |
13 | The order permutations with letters 'a', 'c', and 'b' :
14 | ```
15 | abc
16 | acb
17 | bac
18 | bca
19 | cab
20 | cba
21 | ```
22 |
23 | The answer might not fit in an integer, so return your answer % 1000003
24 |
25 | ## Solution
26 |
27 | ```cpp
28 | #define mod 1000003;
29 |
30 | int fact (int n) {
31 | if (n == 0)
32 | return 1;
33 | else
34 | return (n * fact (n - 1)) % mod;
35 | }
36 |
37 | int Solution::findRank (string A) {
38 | string s = A;
39 | int ans = 0;
40 | int n = s.length ();
41 | for (int i = 0; i < n - 1; i++) {
42 | int c = 0;
43 | for (int j = i + 1; j < n; j++) {
44 | if (s[j] < s[i])
45 | c++;
46 | }
47 | ans += ((c * fact (n - i - 1))) % mod;
48 | }
49 | return (ans + 1) % mod;
50 | }
51 | ```
52 |
--------------------------------------------------------------------------------
/programming/random/0-1-string.md:
--------------------------------------------------------------------------------
1 | # 0/1 String
2 |
3 | https://www.interviewbit.com/problems/0-1-string/
4 |
5 | A "0/1 string" is a string in which every character is either 0 or 1.
6 | There are two operations that can be performed on a 0/1 string:
7 |
8 | * switch: Every 0 becomes 1 and every 1 becomes 0. For example, "100" becomes "011".
9 | * reverse: The string is reversed. For example, "100" becomes "001".
10 |
11 | Consider this infinite sequence of 0/1 strings:
12 |
13 | ```
14 | S0 = ""
15 | S1 = "0"
16 | S2 = "001"
17 | S3 = "0010011"
18 | S4 = "001001100011011"
19 | ...
20 | S(n) = S(n-1) + "0" + switch(reverse(S(n-1)))
21 | ```
22 |
23 | Given an integer A,
24 | find and return the Ath character of Sx, where x = 10^100.
25 |
26 | ### Input Format
27 |
28 | The only argument given is integer A.
29 |
30 | ### Output Format
31 |
32 | Return the total number of digit **1** appearing in all non-negative integers less than or equal to A.
33 |
34 | ### Constraints
35 |
36 | 1 <= A <= 10^9
37 |
38 | ### For Example
39 |
40 | ```
41 | Input 1:
42 | A = 10
43 | Output 1:
44 | 0
45 |
46 | Input 2:
47 | A = 3
48 | Output 2:
49 | 1
50 | ```
51 |
52 | ## Solution
53 |
54 | ### Mine (python)
55 | ```python
56 | class Solution:
57 | def solve(self, k):
58 | return 0 if k & ((k & -k) << 1) == 0 else 1
59 | ````
60 |
--------------------------------------------------------------------------------
/programming/random/another-chocolate-game.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/random/another-chocolate-game.md
--------------------------------------------------------------------------------
/programming/random/bus-and-passenger.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/random/bus-and-passenger.md
--------------------------------------------------------------------------------
/programming/random/check-whether-the-graph-is-bipartide-or-not.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/random/check-whether-the-graph-is-bipartide-or-not.md
--------------------------------------------------------------------------------
/programming/random/device-crossover.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/random/device-crossover.md
--------------------------------------------------------------------------------
/programming/random/elements-which-have-at-least-two-greater-elements.md:
--------------------------------------------------------------------------------
1 | # Elements which have at-least two greater elements
2 |
3 | https://www.interviewbit.com/problems/elements-which-have-at-least-two-greater-elements/
4 |
5 | Given an array of distinct integers A, find and return
6 | all elements in array which have at-least two greater elements than themselves.
7 |
8 | Note: The results should have the order in which they are present in the original array.
9 |
10 | ### Input Format
11 |
12 | The only argument given is the integer array A.
13 |
14 | ### Output Format
15 |
16 | Return the elements which have at-least two greater elements than themselves.
17 |
18 | ### Constraints
19 | ```
20 | 3 <= length of the array <= 100000
21 | -10^9 <= A[i] <= 10^9
22 | ```
23 |
24 | ### For Example
25 | ```
26 | Input 1:
27 | A = [1, 2, 3, 4, 5]
28 | Output 1:
29 | [1, 2, 3]
30 |
31 | Input 2:
32 | A = [5, 17, 100, 11]
33 | Output 2:
34 | [5, 11]
35 | ```
36 |
37 | ## Solution
38 | ### Mine
39 | ```cpp
40 | vector Solution::solve(vector &A) {
41 | A.erase(max_element(A.begin(), A.end()));
42 | A.erase(max_element(A.begin(), A.end()));
43 | return A;
44 | }
45 | ```
46 |
47 | ### Another Mine
48 | ```cpp
49 | vector Solution::solve(vector &A) {
50 | int a = INT_MIN, b = INT_MIN;
51 | for (int x:A) if (x>a) { b=a; a=x; } else if (x>b) b = x;
52 | for (int i=0, k=0; i> dp(n+1, vector(n+1, 0));
36 | for (int i = n-1; i>=0; i--) {
37 | dp[i][i] = 1;
38 | for (int j = i+1; j= B.
8 |
9 | If there isn’t one, return 0 instead.
10 |
11 | ### NOTE
12 |
13 | Your code may be run on multiple testcases ( <= 50 ). Try to come up with an optimised solution.
14 |
15 | ### CONSTRAINTS
16 | ```
17 | 1 <= n (size of array A) <= 10^5
18 | 1 <= A[i] <= 10^4
19 | 1 <= B <= 2*10^9
20 | ```
21 | ### INPUT FORMAT
22 | ```
23 | A : Array containing some integer elements
24 | B : The number by which the sum of contiguous sub-array should be greater
25 | ```
26 | ### SAMPLE INPUT
27 | ```
28 | A : [ 2, 3, 1, 2, 4, 3 ]
29 | B : 7
30 | ```
31 | ### SAMPLE OUTPUT
32 | ```
33 | 2
34 | ```
35 | ### EXPLANATION
36 |
37 | The smallest possible sub array with sum >= 7 is [4,3]
38 |
39 | ## Solution
40 | ### Mine
41 | ```cpp
42 | int Solution::solve(vector &A, int B) {
43 | int res = INT_MAX;
44 | int sum = 0;
45 | for (int i = 0, j = 0; i < A.size(); i++) {
46 | sum += A[i];
47 | while (sum >= B) {
48 | res = min(res, i + 1 - j);
49 | sum -= A[j++];
50 | }
51 | }
52 | return res == INT_MAX ? 0 : res;
53 | }
54 | ```
55 |
--------------------------------------------------------------------------------
/programming/random/most-stones-removed.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/random/most-stones-removed.md
--------------------------------------------------------------------------------
/programming/random/number-of-islands.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/random/number-of-islands.md
--------------------------------------------------------------------------------
/programming/random/palindromic-substrings-count.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/random/palindromic-substrings-count.md
--------------------------------------------------------------------------------
/programming/random/parity-queries.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/random/parity-queries.md
--------------------------------------------------------------------------------
/programming/random/product-array-puzzle.md:
--------------------------------------------------------------------------------
1 | # Product array puzzle
2 |
3 | https://www.interviewbit.com/problems/product-array-puzzle/
4 |
5 | Given an array of integers A, find and return the product array of same size where
6 | i'th element of the product array will be equal to the product of all the elements divided by the i'th element of the array.
7 |
8 | Note: It is always possible to form the product array with integer (32 bit) values.
9 |
10 | ### Input Format
11 |
12 | The only argument given is the integer array A.
13 |
14 | ### Output Format
15 |
16 | Return the product array.
17 |
18 | ### Constraints
19 |
20 | ```
21 | 1 <= length of the array <= 1000
22 | 1 <= A[i] <= 10
23 | ```
24 |
25 | ### For Example
26 | ```
27 | Input 1:
28 | A = [1, 2, 3, 4, 5]
29 | Output 1:
30 | [120, 60, 40, 30, 24]
31 |
32 | Input 2:
33 | A = [5, 1, 10, 1]
34 | Output 2:
35 | [10, 50, 5, 50]
36 | ```
37 |
38 | ## Solution
39 | ### Mine (passes tests)
40 | ```cpp
41 | vector Solution::solve(vector &A) {
42 | long long prod = 1;
43 | for (int x:A) prod *= x;
44 | vector res;
45 | for (int x:A) res.push_back(prod/x);
46 | return res;
47 | }
48 | ```
49 |
50 | ### Optimized (integers)
51 | ```cpp
52 | vector Solution::solve(vector &a) {
53 | int n = a.size();
54 | vector l(n); l[0] = 1;
55 | for (int i = 1; i r(n); r[n-1] = 1;
57 | for (int i = n-2; i>=0; i--) r[i] = a[i+1] * r[i+1];
58 | vector res(n);
59 | for (int i = 0; i < n; i++) res[i] = l[i] * r[i];
60 | return res;
61 | }
62 |
63 | ```
64 |
65 |
--------------------------------------------------------------------------------
/programming/random/rotten-oranges.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/random/rotten-oranges.md
--------------------------------------------------------------------------------
/programming/random/sum-of-all-submatrices.md:
--------------------------------------------------------------------------------
1 | # Sum of all Submatrices
2 |
3 | https://www.interviewbit.com/problems/sum-of-all-submatrices/
4 |
5 | Given a 2D Matrix of dimensions N*N, we need to return sum of all possible submatrices.
6 |
7 | ### Example Input
8 | ```
9 | [ [1,1],
10 | [1,1] ]
11 | ```
12 | ### Example Output
13 | ```
14 | 16
15 | ```
16 |
17 | ### Explanation
18 |
19 | ```
20 | Number of submatrices with 1 elements = 4, so sum of all such submatrices = 4*1 = 4
21 | Number of submatrices with 2 elements = 4, so sum of all such submatrices = 4*2 = 8
22 | Number of submatrices with 3 elements = 0
23 | Number of submatrices with 4 elements = 1, so sum of such submatrix = 4
24 |
25 | Total Sum = 4+8+4 = 16
26 | ```
27 | ## Solution
28 | ### Mine
29 | ```cpp
30 | int Solution::solve(vector > &arr) {
31 | int sum = 0, n = arr.size();
32 | for (int i = 0; i < n; i++)
33 | for (int j = 0; j < n; j++) {
34 | int top_left = (i + 1) * (j + 1);
35 | int bottom_right = (n - i) * (n - j);
36 | sum += (top_left * bottom_right * arr[i][j]);
37 | }
38 | return sum;
39 | }
40 | ```
41 |
42 |
--------------------------------------------------------------------------------
/programming/random/vertex-cover-problem.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joric/interviewbit/4edd853e6b2a9d44a657289036b6fa847d39ffb3/programming/random/vertex-cover-problem.md
--------------------------------------------------------------------------------
/programming/stacks-and-queues/min-stack.md:
--------------------------------------------------------------------------------
1 | # Min Stack
2 |
3 | https://www.interviewbit.com/problems/min-stack
4 |
5 |
6 |
7 | What if you maintaned the current minimum in a variable and only stored
8 | the places where the minimum changes or the element is same as the minimum.
9 |
10 | pop() becomes a little trickier in such a case.
11 | You only pop() from the min stack if the top() of min stack is same as the current minimum.
12 |
13 | Space complexity: O(N + X) where X = number of places where minimum changes or the element is same as the minimum
14 |
15 | ## Solution
16 |
17 | ```cpp
18 |
19 | vector v, v1;
20 |
21 | MinStack::MinStack() {
22 | v.clear();
23 | v1.clear();
24 | }
25 |
26 | void MinStack::push(int x) {
27 | v.push_back(x);
28 | if (v1.empty() || x <= v1.back()) v1.push_back(x);
29 | }
30 |
31 | void MinStack::pop() {
32 | if (!v.empty()) {
33 | if (v.back() == v1.back()) v1.pop_back();
34 | v.pop_back();
35 | }
36 | }
37 |
38 | int MinStack::top() {
39 | if (!v.empty())
40 | return v.back();
41 | else
42 | return -1;
43 | }
44 |
45 | int MinStack::getMin() {
46 | if (!v1.empty())
47 | return v1.back();
48 | else
49 | return -1;
50 | }
51 | ```
--------------------------------------------------------------------------------
/programming/stacks-and-queues/sliding-window-maximum.md:
--------------------------------------------------------------------------------
1 | # Sliding Window Maxiumum
2 |
3 | https://www.interviewbit.com/problems/sliding-window-maxiumum
4 |
5 |
6 |
7 | The double-ended queue is the perfect data structure for this problem.
8 | It supports insertion/deletion from the front and back.
9 | The trick is to find a way such that the largest element in the window
10 | would always appear in the front of the queue. How would you maintain
11 | this requirement as you push and pop elements in and out of the queue?
12 |
13 | You might notice that there are some redundant elements in the queue
14 | that we shouldn't even consider about. For example, if the current
15 | queue has the elements: [10 5 3], and a new element in the window has
16 | the element 11. Now, we could have emptied the queue without considering
17 | elements 10, 5, and 3, and insert only element 11 into the queue.
18 |
19 | A natural way most people would think is to try to maintain the queue
20 | size the same as the window's size. Try to break away from this thought
21 | and try to think outside of the box. Removing redundant elements and storing
22 | only elements that need to be considered in the queue is the key to achieve
23 | the efficient O(n) solution.
24 |
25 | ## Solution
26 |
27 | ```cpp
28 |
29 | // editorial
30 |
31 | vector Solution::slidingMaximum(vector &A, int w) {
32 | int n = A.size();
33 | vector B;
34 | if (n < w) return B;
35 | B.resize(n - w + 1);
36 | deque q;
37 | for (int i = 0; i < w; i++) {
38 | while (!q.empty() && A[i] >= A[q.back()])
39 | q.pop_back();
40 | q.push_back(i);
41 | }
42 | for (int i = w; i < n; i++) {
43 | B[i - w] = A[q.front()];
44 | while (!q.empty() && A[i] >= A[q.back()])
45 | q.pop_back();
46 | while (!q.empty() && q.front() <= i - w)
47 | q.pop_front();
48 | q.push_back(i);
49 | }
50 | B[n - w] = A[q.front()];
51 | return B;
52 | }
53 |
54 | ```
--------------------------------------------------------------------------------
/programming/strings/amazing-subarrays.md:
--------------------------------------------------------------------------------
1 | # Amazing Subarrays
2 |
3 | https://www.interviewbit.com/problems/amazing-subarrays
4 |
5 |
6 |
7 | You are given a string S, and you have to find all the amazing substrings of S.
8 |
9 | Amazing Substring is one that starts with a vowel (a, e, i, o, u, A, E, I, O, U).
10 |
11 | ## Solution
12 |
13 | ```cpp
14 |
15 | bool isVowel(char c) {
16 | //return (c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='A' || c=='E' || c=='I' || c=='O' || c=='U');
17 | return string("aeiouAEIOU").find(c)!=string::npos;
18 | }
19 |
20 | int Solution::solve(string A) {
21 | int sum = 0, n=A.size();
22 | for (int i = 0; i 0) {
45 | while (num >= key[iter]) {
46 | ret += value[iter];
47 | num -= key[iter];
48 | }
49 | iter++;
50 | }
51 | return ret;
52 | }
53 | ```
--------------------------------------------------------------------------------
/programming/strings/length-of-last-word.md:
--------------------------------------------------------------------------------
1 | # Length Of Last Word
2 |
3 | https://www.interviewbit.com/problems/length-of-last-word
4 |
5 |
6 |
7 | hint1
8 |
9 | Not using library functions and traversing the string only once is the main twist here.
10 |
11 | Try to answer these questions while using single loop:
12 | How can you detect the end of the string?
13 | How can you detect where the word begins?
14 |
15 | hint2
16 |
17 | As said before, this problem does not allow using library functions.
18 |
19 | What if you maintained the length of the current word?
20 |
21 | You reset the length of the word when the next word begins (When does a new word begin?)
22 |
23 | Return the last length you have.
24 |
25 | ## Solution
26 |
27 | ```cpp
28 |
29 | /* editorial */
30 |
31 | int Solution::lengthOfLastWord(const string A) {
32 | const char * s = A.c_str();
33 | int len = 0;
34 | while (*s) {
35 | if (*s != ' ') {
36 | len++;
37 | s++;
38 | continue;
39 | }
40 | s++;
41 | if (*s && *s != ' ')
42 | len = 0;
43 | }
44 | return len;
45 | }
46 |
47 | /* my solution */
48 |
49 | int Solution::lengthOfLastWord(const string A) {
50 | int n = A.length();
51 | if (n == 0)
52 | return 0;
53 |
54 | int i = n - 1;
55 | while (i != 0 && A[i] == ' ')
56 | i--;
57 |
58 | int count = 0;
59 | while (A[i] != ' ') {
60 | count++;
61 | i--;
62 | if (i < 0)
63 | break;
64 | }
65 |
66 | return count;
67 | }
68 | ```
--------------------------------------------------------------------------------
/programming/strings/minimum-characters-required-to-make-a-string-palindromic.md:
--------------------------------------------------------------------------------
1 | # Minimum Characters Required To Make a String Palindromic
2 |
3 | https://www.interviewbit.com/problems/minimum-characters-required-to-make-a-string-palindromic
4 |
5 |
6 | You are given a string. The only operation allowed is to insert characters in the beginning of the string.
7 | How many minimum characters are needed to be inserted to make the string a palindrome string
8 |
9 | editorial:
10 | ## Solution
11 |
12 | ```cpp
13 |
14 | int Solution::solve(string A) {
15 | int start = 0, end = A.length() - 1;
16 | int temp_end = end;
17 |
18 | /*Idea is to find longest palindrome length starting from index 0.
19 | Difference of this length from string length is the required value */
20 |
21 | while (start <= temp_end) {
22 | if (A[start] == A[temp_end]) {
23 | start++;
24 | temp_end--;
25 | } else {
26 | start = 0;
27 | temp_end = --end;
28 | }
29 | }
30 |
31 | return A.length() - (end + 1);
32 | }
33 |
34 | /* --- */
35 |
36 | bool ispalindrome(string s) {
37 | int l = s.length();
38 | for (int i = 0, j = l - 1; i <= j; i++, j--)
39 | if (s[i] != s[j])
40 | return false;
41 | return true;
42 | }
43 |
44 | int Solution::solve(string s) {
45 | int cnt = 0;
46 | while (s.length() > 0) {
47 | if (ispalindrome(s))
48 | break;
49 | else {
50 | s.erase(s.begin() + s.length() - 1);
51 | cnt++;
52 | }
53 | }
54 | return cnt;
55 | }
56 | ```
--------------------------------------------------------------------------------
/programming/strings/palindrome-string.md:
--------------------------------------------------------------------------------
1 | # Palindrome String
2 |
3 | https://www.interviewbit.com/problems/palindrome-string
4 |
5 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
6 |
7 | Example:
8 |
9 | `A man, a plan, a canal: Panama` is a palindrome.
10 |
11 | `race a car` is not a palindrome.
12 |
13 | Return 0 / 1 ( 0 for false, 1 for true ) for this problem
14 |
15 | ## Hint 1
16 |
17 | Maintain 2 pointers, one from the begining and one from the end of the string. How to handle the corner cases?
18 |
19 |
20 | ## Solution Approach
21 |
22 | This is a fairly simple question.
23 |
24 | You need to maintain 2 pointers, one from the beginning and one from the end.
25 |
26 | At every iteration, after skipping the non alphanumeric characters, both the characters should match.
27 |
28 | Have you considered empty strings?
29 |
30 | Empty strings are palindromes. This is however, a nice question for clarification from the interviewer.
31 |
32 | Note:
33 |
34 | 1. Are you correctly skipping the non alphanumeric characters?
35 |
36 | 2. Are you correctly handling whitespaces?
37 |
38 |
39 | ## Solution
40 |
41 | ```cpp
42 | int Solution::isPalindrome(string A) {
43 | for (int i=0, j=A.length()-1; i> word;
15 | if (!res.empty())
16 | word += " ";
17 | res = word + res;
18 | }
19 | A = res;
20 | }
21 | ```
22 | ### Editorial
23 |
24 | ```cpp
25 | void Solution::reverseWords(string &a) {
26 | int n = a.size();
27 | int i = 0, in = 0;
28 | while (i < n) {
29 | int start;
30 | if (a[i] != ' ') {
31 | start = i;
32 | int end = start;
33 | i++;
34 | while (i < n && a[i] != ' ') {
35 | end++;
36 | i++;
37 | }
38 | while (start <= end) {
39 | char temp = a[start];
40 | a[start] = a[end];
41 | a[end] = temp;
42 | start++;
43 | end--;
44 | }
45 |
46 | } else
47 | i++;
48 | }
49 | //cout << a << endl;
50 | int start = 0, end = n - 1;
51 | while (start < end) {
52 | char temp = a[start];
53 | a[start] = a[end];
54 | a[end] = temp;
55 | start++;
56 | end--;
57 | }
58 | i = 0;
59 | while (i < n) {
60 | while (i < n && a[i] == ' ')
61 | i++;
62 | if (i != n && in != 0)
63 | a[in++] = ' ';
64 | while (i < n && a[i] != ' ') {
65 | a[in] = a[i];
66 | in++;
67 | i++;
68 | }
69 | }
70 | a.erase(a.begin() + in, a.end());
71 | }
72 | ```
73 |
--------------------------------------------------------------------------------
/programming/strings/roman-to-integer.md:
--------------------------------------------------------------------------------
1 | # Roman To Integer
2 |
3 | https://www.interviewbit.com/problems/roman-to-integer
4 |
5 | editorial */
6 |
7 | class Solution {
8 | public:
9 | int romanToInt(string s) {
10 | int num = 0;
11 | int size = s.size();
12 |
13 | for (int i = 0; i < size; i++) {
14 | // Does lesser value precede higher value ?
15 | if (i < (size - 1) && romanCharToInt(s[i]) < romanCharToInt(s[i + 1])) {
16 | num -= romanCharToInt(s[i]);
17 | } else {
18 | num += romanCharToInt(s[i]);
19 | }
20 | }
21 | return num;
22 | }
23 |
24 | int romanCharToInt(char c) {
25 | switch (c) {
26 | case 'I': return 1;
27 | case 'V': return 5;
28 | case 'X': return 10;
29 | case 'L': return 50;
30 | case 'C': return 100;
31 | case 'D': return 500;
32 | case 'M': return 1000;
33 | default: return 0;
34 | }
35 | }
36 | };
37 |
38 | /* my solution */
39 |
40 | int Solution::romanToInt(string s) {
41 | unordered_map m = { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } };
42 | int x = 0;
43 | for (int i = 0; i < s.length(); i++)
44 | x += i + 1 < s.length() && m[s[i]] < m[s[i + 1]] ? m[s[i + 1]] - m[s[i++]]: m[s[i]];
45 | return x;
46 | }
47 |
48 | /* another solution */
49 |
50 | int Solution::romanToInt(string s) {
51 | unordered_map m = { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } };
52 | int x = 0, n = s.size();
53 | for (int i = 0; i < n; i++)
54 | x += i < n-1 && m[s[i]] < m[s[i+1]] ? - m[s[i]]: m[s[i]];
55 | return x;
56 | }
57 | ```
--------------------------------------------------------------------------------
/programming/strings/valid-ip-addresses.md:
--------------------------------------------------------------------------------
1 | # Valid Ip Addresses
2 |
3 | https://www.interviewbit.com/problems/valid-ip-addresses
4 |
5 | Given a string containing only digits, restore it by returning all possible valid IP address combinations.
6 |
7 | A valid IP address must be in the form of A.B.C.D, where A,B,C and D are numbers from 0-255. The numbers cannot be 0 prefixed unless they are 0.
8 |
9 | ### Example
10 |
11 | Given `25525511135`, return `["255.255.11.135", "255.255.111.35"]`
12 |
13 | (Make sure the returned strings are sorted in order)
14 |
15 | ## Solution
16 |
17 | ```cpp
18 |
19 | bool isValid(string s) {
20 | if (s.size() > 1 && s[0] == '0')
21 | return false;
22 | if (stoi(s) <= 255 && stoi(s) >= 0)
23 | return true;
24 | else
25 | return false;
26 | }
27 |
28 | vector Solution::restoreIpAddresses(string s) {
29 | vector ans;
30 | if (s.size() > 12 || s.size() < 4)
31 | return ans;
32 |
33 | for (int i = 1; i < 4; i++) {
34 | string first = s.substr(0, i);
35 | if (!isValid(first))
36 | continue;
37 | for (int j = 1; i + j < s.size() && j < 4; j++) {
38 | string second = s.substr(i, j);
39 | if (!isValid(second))
40 | continue;
41 | for (int k = 1; i + j + k < s.size() && k < 4; k++) {
42 | string third = s.substr(i + j, k);
43 | string fourth = s.substr(i + j + k);
44 | if (isValid(third) && isValid(fourth)) {
45 | string current = first + "." + second + "." + third + "." + fourth;
46 | ans.push_back(current);
47 | }
48 | }
49 | }
50 | }
51 | return ans;
52 | }
53 | ```
--------------------------------------------------------------------------------
/programming/strings/zigzag-string.md:
--------------------------------------------------------------------------------
1 | # Zigzag String
2 |
3 | https://www.interviewbit.com/problems/zigzag-string
4 |
5 |
6 | More of a simulation problem. Think how you can simulate this?
7 |
8 | Just look at simply simulating what is being told in the problem.
9 |
10 | Follow the simple steps:
11 |
12 | You need to maintain numRows number of strings S[numRows].
13 | And then populating string S in each row in zigzag fashion.
14 | Finally concatenate S[0] .. S[numRows-1] to get the answer.
15 | ## Solution
16 |
17 | ```cpp
18 |
19 | string Solution::convert(string s, int rows) {
20 | string ans;
21 | if(rows<=1)
22 | return s;
23 | int i=0,j=0, n = s.length(), l = rows-1;
24 | while(ileft && !node->right)
13 | return 1;
14 |
15 | auto l = 1 + height(node->left);
16 | auto r = 1 + height(node->right);
17 |
18 | if (l < 0 || r < 0)
19 | return INT_MIN;
20 | if (abs(l - r) > 1)
21 | return INT_MIN;
22 | return max(l, r);
23 | }
24 | int Solution::isBalanced(TreeNode *A) {
25 | if (height(A) < 0)
26 | return 0;
27 | return 1;
28 | }
29 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/flatten-binary-tree-to-linked-list.md:
--------------------------------------------------------------------------------
1 | # Flatten Binary Tree To Linked List
2 |
3 | https://www.interviewbit.com/problems/flatten-binary-tree-to-linked-list
4 |
5 |
6 | Given a binary tree, flatten it to a linked list in-place.
7 |
8 | Example :
9 | Given
10 |
11 |
12 | 1
13 | / \
14 | 2 5
15 | / \ \
16 | 3 4 6
17 | The flattened tree should look like:
18 |
19 | 1
20 | \
21 | 2
22 | \
23 | 3
24 | \
25 | 4
26 | \
27 | 5
28 | \
29 | 6
30 | Note that the left child of all nodes should be NULL.
31 |
32 | ## Solution
33 |
34 | ```cpp
35 |
36 | /**
37 | * Definition for binary tree
38 | * struct TreeNode {
39 | * int val;
40 | * TreeNode *left;
41 | * TreeNode *right;
42 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
43 | * };
44 | */
45 |
46 | // Recursive solution - Uses extra auxiliary space in stack for recursive calls.
47 | /*void fillPreorder(vector& preOrder, TreeNode* root)
48 | {
49 | if (!root)
50 | return;
51 | preOrder.emplace_back(root);
52 | fillPreorder(preOrder, root->left);
53 | fillPreorder(preOrder, root->right);
54 | }
55 | TreeNode* Solution::flatten(TreeNode* A) {
56 | if (!A)
57 | return A;
58 | vector preOrder;
59 | fillPreorder(preOrder, A);
60 | TreeNode* root = A;
61 | for (auto i = 1; ileft = NULL;
64 | A->right = preOrder[i];
65 | A = A->right;
66 | }
67 | A->left = NULL;
68 | return root;
69 | }*/
70 |
71 | // Iterative solution - Solves inplace without using extra auxiliary space for recursion.
72 | TreeNode* Solution::flatten(TreeNode* A) {
73 | if (!A)
74 | return A;
75 | TreeNode* root = A;
76 |
77 | while (A)
78 | {
79 | if (A->left)
80 | {
81 | TreeNode* rightSubTree = A->left;
82 | while (rightSubTree->right)
83 | rightSubTree = rightSubTree->right;
84 | rightSubTree->right = A->right;
85 | A->right = A->left;
86 | A->left = NULL;
87 | }
88 | A = A->right;
89 | }
90 | return root;
91 | }
92 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/identical-binary-trees.md:
--------------------------------------------------------------------------------
1 | # Identical Binary Tree
2 |
3 | https://www.interviewbit.com/problems/identical-binary-tree
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | int Solution::isSameTree(TreeNode* A, TreeNode* B) {
10 | if (!A && !B)
11 | return true;
12 | if (!A || !B)
13 | return false;
14 | if (A->val != B->val)
15 | return false;
16 | return isSameTree(A->left, B->left) && isSameTree(A->right, B->right);
17 | }
18 |
19 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/inorder-traversal.md:
--------------------------------------------------------------------------------
1 | # Inorder Traversal
2 |
3 | https://www.interviewbit.com/problems/inorder-traversal
4 |
5 |
6 | You can do this problem easily but as stated in problem recursion is not allowed here.
7 |
8 | Stack can help you to avoid recursion. How?
9 |
10 | Think stack.
11 |
12 | Recursive call would look something like this :
13 |
14 | inorderprint(root->left);
15 | print(root->val);
16 | inorderprint(root->right);
17 |
18 | Instead of calling the functions, can you put the nodes on a stack and process them ?
19 |
20 | How would your solution work if you were allowed to change the original tree ?
21 | How would it work if you were not allowed to change the tree but use additional memory ( track the number of times a node has appeared in the tree ) ?
22 | How would it work if you were not even allowed the extra memory ?
23 |
24 | ## Solution
25 |
26 | ```cpp
27 | // editorial
28 |
29 | vector inorderTraversal(TreeNode *root) {
30 | vector vector;
31 | stack stack;
32 | TreeNode *pCurrent = root;
33 |
34 | while (!stack.empty() || pCurrent) {
35 | if (pCurrent) {
36 | stack.push(pCurrent);
37 | pCurrent = pCurrent->left;
38 | } else {
39 | TreeNode *pNode = stack.top();
40 | vector.push_back(pNode->val);
41 | stack.pop();
42 | pCurrent = pNode->right;
43 | }
44 | }
45 | return vector;
46 | }
47 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/invert-the-binary-tree.md:
--------------------------------------------------------------------------------
1 | # Invert The Binary Tree
2 |
3 | https://www.interviewbit.com/problems/invert-the-binary-tree
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | TreeNode* Solution::invertTree(TreeNode* A) {
10 | if (!A)
11 | return 0;
12 | TreeNode * left = invertTree(A->left);
13 | TreeNode * right = invertTree(A->right);
14 | A->left = right;
15 | A->right = left;
16 | return A;
17 | }
18 |
19 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/max-depth-of-binary-tree.md:
--------------------------------------------------------------------------------
1 | # Max Depth Of Binary Tree
2 |
3 | https://www.interviewbit.com/problems/max-depth-of-binary-tree
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 |
10 |
11 | /**
12 | * Definition for binary tree
13 | * struct TreeNode {
14 | * int val;
15 | * TreeNode *left;
16 | * TreeNode *right;
17 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
18 | * };
19 | */
20 |
21 | int depth(TreeNode *root) {
22 | if (!root)
23 | return 0;
24 | return 1 + max(depth(root->left), depth(root->right));
25 | }
26 |
27 | int Solution::maxDepth(TreeNode* A) {
28 | return depth(A);
29 | }
30 |
31 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/min-depth-of-binary-tree.md:
--------------------------------------------------------------------------------
1 | # Min Depth Of Binary Tree
2 |
3 | https://www.interviewbit.com/problems/min-depth-of-binary-tree
4 |
5 | ```cpp
6 | /*
7 | * Definition for binary tree
8 | * struct TreeNode {
9 | * int val;
10 | * TreeNode *left;
11 | * TreeNode *right;
12 | * TreeNode(int x): val(x), left(NULL), right(NULL) {}
13 | * };
14 | */
15 |
16 | // editorial
17 |
18 | int Solution::minDepth(TreeNode *root) {
19 | if (!root) return 0;
20 | if (!root->left && !root->right) return 1;
21 | if (!root->left) return 1 + minDepth(root->right);
22 | if (!root->right) return 1 + minDepth(root->left);
23 | return 1 + min(minDepth(root->left), minDepth(root->right));
24 | }
25 |
26 |
27 |
28 | // mine
29 |
30 | int depth(TreeNode *root) {
31 | if (!root)
32 | return INT_MAX;
33 | if (!root->left && !root->right)
34 | return 1;
35 | return 1 + min(depth(root->left), depth(root->right));
36 | }
37 |
38 | int Solution::minDepth(TreeNode* A) {
39 | if (!A)
40 | return 0;
41 | else if (!A->left && !A->right)
42 | return 1;
43 | return depth(A);
44 | }
45 | ```
46 |
--------------------------------------------------------------------------------
/programming/tree-data-structure/next-greater-number-bst.md:
--------------------------------------------------------------------------------
1 | # Next Greater Number Bst
2 |
3 | https://www.interviewbit.com/problems/next-greater-number-bst
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | class Solution {
10 | public:
11 | TreeNode *Find(TreeNode *root, int data) {
12 | while (root != NULL && root->val != data) {
13 | if (data < root->val)
14 | root = root->left;
15 | else
16 | root = root->right;
17 | }
18 | if (root != NULL && root->val == data) return root;
19 | return NULL;
20 | }
21 |
22 | TreeNode *FindMin(TreeNode *root) {
23 | while (root->left != NULL) root = root->left;
24 | return root;
25 | }
26 |
27 | TreeNode *getSuccessor(TreeNode *root, int data) {
28 | // Search the node O(h)
29 | TreeNode *current = Find(root, data);
30 | if (current == NULL) return NULL;
31 | if (current->right != NULL) { // Case 1 : Node has right subtree
32 | return FindMin(current->right);
33 | } else {
34 | TreeNode *successor = NULL, *ancestor = root;
35 | while (ancestor != current) {
36 | if (data < ancestor->val) {
37 | successor = ancestor; // so far this is the deepest node for which current node is in left.
38 | ancestor = ancestor->left;
39 | } else
40 | ancestor = ancestor->right;
41 | }
42 | return successor;
43 | }
44 | }
45 | };
46 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/path-sum.md:
--------------------------------------------------------------------------------
1 | # Path Sum
2 |
3 | https://www.interviewbit.com/problems/path-sum
4 |
5 |
6 |
7 | Can you traverse the tree while keeping the sum from root to current node?
8 |
9 | How can you check if you have reached the leaf or not?
10 |
11 |
12 | Recursion might make this problem much easier to solve.
13 | You just need to keep a track of the sum from the root to the current node.
14 | Then it becomes a question of just checking if the current node is a leaf node, and if so, do the sum match.
15 |
16 |
17 |
18 | ## Solution
19 |
20 | ```cpp
21 |
22 | // editorial
23 |
24 | int Solution::hasPathSum(TreeNode *root, int sum) {
25 | if (!root) return false;
26 | if (!root->left && !root->right)
27 | return sum == root->val;
28 | int remainingSum = sum - root->val;
29 | return hasPathSum(root->left, remainingSum) || hasPathSum(root->right, remainingSum);
30 | }
31 |
32 | //////////////////////////////////////////////////////////
33 |
34 | int pathsum(TreeNode* root, int sum, const int& target) {
35 | if (!root)
36 | return false;
37 | sum += root->val;
38 | if (!root->left && !root->right)
39 | return sum == target;
40 | return pathsum(root->left, sum, target) || pathsum(root->right, sum, target);
41 | }
42 | int Solution::hasPathSum(TreeNode* root, int target) {
43 | if (!root)
44 | return 0;
45 | return pathsum(root, 0, target);
46 | }
47 |
48 |
49 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/postorder-traversal.md:
--------------------------------------------------------------------------------
1 | # Postorder Traversal
2 |
3 | https://www.interviewbit.com/problems/postorder-traversal
4 |
5 |
6 | You can do this problem easily but as stated in problem recursion is not allowed here.
7 |
8 | Stack can help you to avoid recursion. How?
9 |
10 |
11 | Think stack.
12 |
13 | Recursive call would look something like this :
14 |
15 | postorderprint(root->left);
16 | postorderprint(root->right);
17 | print(root->val);
18 |
19 | Instead of calling the functions, can you put the nodes on a stack and process them ?
20 | Would the solution be easier if you were to print the reverse of the asked ?
21 |
22 |
23 |
24 | pre-order traversal is root-left-right, and post order is left-right-root. modify the code for pre-order to make it root-right-left, and then reverse the output so that we can get left-right-root .
25 |
26 | Create an empty stack, Push root node to the stack.
27 | Do following while stack is not empty.
28 |
29 | 2.1. pop an item from the stack and print it.
30 |
31 | 2.2. push the left child of popped item to stack.
32 |
33 | 2.3. push the right child of popped item to stack.
34 |
35 | reverse the ouput.
36 |
37 | ## Solution
38 |
39 | ```cpp
40 |
41 | // editorial
42 |
43 | vector postorderTraversal(TreeNode *root) {
44 | stack nodeStack;
45 | vector result;
46 | //base case
47 | if (root == NULL)
48 | return result;
49 | nodeStack.push(root);
50 | while (!nodeStack.empty()) {
51 | TreeNode *node = nodeStack.top();
52 | result.push_back(node->val);
53 | nodeStack.pop();
54 | if (node->left)
55 | nodeStack.push(node->left);
56 | if (node->right)
57 | nodeStack.push(node->right);
58 | }
59 | reverse(result.begin(), result.end());
60 | return result;
61 | }
62 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/preorder-traversal.md:
--------------------------------------------------------------------------------
1 | # Preorder Traversal
2 |
3 | https://www.interviewbit.com/problems/preorder-traversal
4 |
5 |
6 | ## Hint 1
7 | You can do this problem easily but as stated in problem recursion is not allowed here.
8 |
9 | Stack can help you to avoid recursion. How?
10 |
11 |
12 | Think stack.
13 |
14 | Recursive call would look something like this :
15 |
16 | print(root->val);
17 | preorderprint(root->left);
18 | preorderprint(root->right);
19 |
20 | Instead of calling the functions, can you put the nodes on a stack and process them ?
21 |
22 |
23 |
24 | ## Solution
25 |
26 | ```cpp
27 |
28 | // editorial
29 |
30 | vector Solution::preorderTraversal(TreeNode *root) {
31 | vector res;
32 | stack nodeStack;
33 |
34 | while (nodeStack.size() != 0 || root != NULL) {
35 | if (root == NULL) {
36 | root = nodeStack.top();
37 | nodeStack.pop();
38 | } else {
39 | res.push_back(root->val);
40 | if (root->right != NULL)
41 | nodeStack.push(root->right);
42 | root = root->left;
43 | }
44 | }
45 | return res;
46 | }
47 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/root-to-leaf-paths-with-sum.md:
--------------------------------------------------------------------------------
1 | # Root to Leaf Paths With Sum
2 |
3 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
4 |
5 | For example:
6 | Given the below binary tree and sum = 22,
7 | ```
8 | 5
9 | / \
10 | 4 8
11 | / / \
12 | 11 13 4
13 | / \ / \
14 | 7 2 5 1
15 | ```
16 | return
17 | ```
18 | [
19 | [5,4,11,2],
20 | [5,8,4,5]
21 | ]
22 | ```
23 | ## Hint 1
24 |
25 | Hint : Think recursion.
26 |
27 | What if in your recursive function, you already know about the sum till the current node.
28 |
29 | GOTCHAS:
30 |
31 | If you are using C++, make sure to pass the array by reference.
32 |
33 | ## Solution Approach
34 |
35 | Recursion might make this problem much easier to solve.
36 |
37 | You just need to keep a track of :
38 | 1) the sum from the root to the current node.
39 | 2) The elements encountered from the root to this node.
40 |
41 | Then it becomes a question of just checking if the current node is a leaf node, and if so, do the sum match.
42 | If sums match, then you append the current elements from root to this node to the answer list.
43 |
44 | Check for a node being a leaf:
45 |
46 | ```
47 | node->left == NULL && node->right == NULL
48 | ```
49 |
50 | ## Solution
51 |
52 | ```cpp
53 | void rootleaf( TreeNode *pvar, int sum, vector> &ans, vector curr ) {
54 | if(!pvar)
55 | return;
56 | curr.push_back( pvar->val );
57 | rootleaf( pvar->left, sum - pvar->val, ans, curr );
58 | rootleaf( pvar->right, sum - pvar->val, ans, curr );
59 | if( pvar->left == NULL && pvar->right == NULL && ( (sum - pvar->val ) == 0 ) )
60 | ans.push_back( curr );
61 | }
62 |
63 | vector> Solution::pathSum(TreeNode* A, int B) {
64 | vector< vector > ans;
65 | vector curr;
66 | rootleaf( A, B, ans, curr );
67 | return ans;
68 | }
69 | ```
70 |
--------------------------------------------------------------------------------
/programming/tree-data-structure/shortest-unique-prefix.md:
--------------------------------------------------------------------------------
1 | # Shortest Unique Prefix
2 |
3 | https://www.interviewbit.com/problems/shortest-unique-prefix
4 |
5 |
6 | Find shortest unique prefix to represent each word in the list.
7 |
8 | Example:
9 |
10 | Input: [zebra, dog, duck, dove]
11 | Output: {z, dog, du, dov}
12 | where we can see that
13 | zebra = z
14 | dog = dog
15 | duck = du
16 | dove = dov
17 | NOTE: Assume that no word is prefix of another. In other words, the representation is always possible.
18 |
19 | ## Solution
20 |
21 | ```cpp
22 |
23 | struct Trie
24 | {
25 | Trie *edges[26];
26 | int words;
27 | Trie()
28 | {
29 | for (auto i = 0; i<26; ++i)
30 | edges[i] = NULL;
31 | words = 0;
32 | }
33 | };
34 |
35 | void addToTrie(Trie* head, string s)
36 | {
37 | int n = s.length();
38 | Trie *current = head;
39 |
40 | for (auto i = 0; iwords += 1;
43 | if (!current->edges[s[i]-'a'])
44 | current->edges[s[i]-'a'] = new Trie();
45 | current = current->edges[s[i]-'a'];
46 | }
47 | }
48 |
49 | string findPrefix(Trie* head, string s)
50 | {
51 | int n = s.length();
52 | string prefix = "";
53 | Trie *current = head;
54 | int i = 0;
55 | current = current->edges[s[i]-'a'];
56 | prefix += s[i];
57 |
58 | for (i = 1; iwords == 1)
61 | return prefix;
62 | current = current->edges[s[i]-'a'];
63 | prefix += s[i];
64 | }
65 | return prefix;
66 | }
67 |
68 | vector Solution::prefix(vector &A) {
69 | vector res;
70 | if (A.empty())
71 | return res;
72 | Trie *head = new Trie();
73 |
74 | auto size = A.size();
75 | for (auto i = 0; i &data, int i, int j) {
27 | if (i>j)
28 | return 0;
29 | int m = (i + j) / 2;
30 | TreeNode * node = new TreeNode(data[m]);
31 | node->left = make_bst(data, i, m - 1);
32 | node->right = make_bst(data, m + 1, j);
33 | return node;
34 | }
35 |
36 | TreeNode* Solution::sortedArrayToBST(const vector &A) {
37 | return make_bst(A, 0, A.size()-1);
38 | }
39 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/sum-root-to-leaf-numbers.md:
--------------------------------------------------------------------------------
1 | # Sum Root To Leaf Numbers
2 |
3 | https://www.interviewbit.com/problems/sum-root-to-leaf-numbers
4 |
5 | ```cpp
6 |
7 | // editorial
8 |
9 | int sumNumbers(TreeNode *root, int curSum) {
10 | if (root == NULL) return curSum;
11 | curSum = (curSum * 10 + root->val) % 1003;
12 | if (root->left == NULL && root->right == NULL) return curSum;
13 | if (!root->left) return sumNumbers(root->right, curSum);
14 | if (!root->right) return sumNumbers(root->left, curSum);
15 | return (sumNumbers(root->left, curSum) + sumNumbers(root->right, curSum)) % 1003;
16 | }
17 |
18 | int Solution::sumNumbers(TreeNode *root) {
19 | return sumNumbers(root, 0);
20 | }
21 |
22 |
23 |
24 |
25 | ///////////////
26 |
27 |
28 | int sum(TreeNode* root, int total) {
29 | if (!root)
30 | return 0;
31 |
32 | total = ((total*10)%1003 + root->val)%1003;
33 | if (!root->left && !root->right)
34 | return total;
35 | return (sum(root->left, total)%1003 + sum(root->right, total)%1003)%1003;
36 | }
37 |
38 | int Solution::sumNumbers(TreeNode* A) {
39 | return sum(A, 0);
40 | }
41 |
42 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/symmetric-binary-tree.md:
--------------------------------------------------------------------------------
1 | # Symmetric Binary Tree
2 |
3 | https://www.interviewbit.com/problems/symmetric-binary-tree
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | bool symmetric(TreeNode* a, TreeNode* b) {
10 | if (!a || !b)
11 | return a == b;
12 | if (a->val != b->val)
13 | return false;
14 | return symmetric(a->left, b->right) && symmetric(a->right, b->left);
15 | }
16 |
17 | int Solution::isSymmetric(TreeNode* A) {
18 | return !A || symmetric(A->left, A->right);
19 | }
20 |
21 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/vertical-order-traversal-of-binary-tree.md:
--------------------------------------------------------------------------------
1 | # Vertical Order Traversal
2 |
3 | https://www.interviewbit.com/problems/vertical-order-traversal
4 |
5 |
6 | ## Solution
7 |
8 | ```cpp
9 | // editorial
10 |
11 | vector> Solution::verticalOrderTraversal(TreeNode *root) {
12 | vector> result;
13 | if (!root)
14 | return result;
15 | map> m; // sorted by key order
16 | queue> q;
17 | q.push(make_pair(root, 0));
18 | while (!q.empty()) {
19 | auto front = q.front();
20 | q.pop();
21 | TreeNode *node = front.first;
22 | int height = front.second;
23 | m[height].push_back(node->val);
24 | if (node->left)
25 | q.push(make_pair(node->left, height - 1));
26 | if (node->right)
27 | q.push(make_pair(node->right, height + 1));
28 | }
29 | for (auto &x : m)
30 | result.push_back(x.second);
31 | return result;
32 | }
33 |
34 | // mine
35 |
36 | vector> Solution::verticalOrderTraversal(TreeNode *root) {
37 | vector> res;
38 |
39 | if (!root)
40 | return res;
41 |
42 | map> m;
43 | int hd = 0;
44 |
45 | queue> que;
46 | que.push(make_pair(root, hd));
47 |
48 | while (!que.empty()) {
49 | // pop from queue front
50 | pair temp = que.front();
51 | que.pop();
52 | hd = temp.second;
53 | TreeNode *node = temp.first;
54 |
55 | // insert this node's data in vector of hash
56 | m[hd].push_back(node->val);
57 |
58 | if (node->left != NULL)
59 | que.push(make_pair(node->left, hd - 1));
60 | if (node->right != NULL)
61 | que.push(make_pair(node->right, hd + 1));
62 | }
63 |
64 | for (auto &x : m) {
65 | vector v;
66 | for (int i = 0; i < x.second.size(); ++i)
67 | v.push_back(x.second[i]);
68 | res.push_back(v);
69 | }
70 |
71 | return res;
72 | }
73 | ```
--------------------------------------------------------------------------------
/programming/tree-data-structure/zigzag-level-order-traversal-bt.md:
--------------------------------------------------------------------------------
1 | # Zigzag Level Order Traversal Bt
2 |
3 | https://www.interviewbit.com/problems/zigzag-level-order-traversal-bt
4 |
5 | Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
6 |
7 | Example:
8 | Given binary tree
9 | ```
10 | 3
11 | / \
12 | 9 20
13 | / \
14 | 15 7
15 | ```
16 | return
17 | ```
18 | [
19 | [3],
20 | [20, 9],
21 | [15, 7]
22 | ]
23 | ```
24 |
25 | ## Solution
26 |
27 | ```cpp
28 |
29 | /**
30 | * Definition for binary tree
31 | * struct TreeNode {
32 | * int val;
33 | * TreeNode *left;
34 | * TreeNode *right;
35 | * TreeNode(int x): val(x), left(NULL), right(NULL) {}
36 | * };
37 | */
38 | int height(TreeNode* A)
39 | {
40 | if (!A)
41 | return 0;
42 | return 1 + max(height(A->left), height(A->right));
43 | }
44 |
45 | void levelTraversal(vector& res, TreeNode* A, int level, bool inverse)
46 | {
47 | if (!A)
48 | return;
49 | if (level == 1)
50 | res.emplace_back(A->val);
51 | else
52 | {
53 | if (inverse)
54 | {
55 | levelTraversal(res, A->right, level-1, inverse);
56 | levelTraversal(res, A->left, level-1, inverse);
57 | }
58 | else
59 | {
60 | levelTraversal(res, A->left, level-1, inverse);
61 | levelTraversal(res, A->right, level-1, inverse);
62 | }
63 | }
64 | }
65 |
66 | vector > Solution::zigzagLevelOrder(TreeNode* A) {
67 | int levels = height(A);
68 | vector > res;
69 | for (auto h = 1; h<=levels; ++h)
70 | {
71 | bool inverse = false;
72 | vector row;
73 | if (h%2 == 0)
74 | inverse = true;
75 | levelTraversal(row, A, h, inverse);
76 | res.emplace_back(row);
77 | }
78 | return res;
79 | }
80 | ```
81 |
--------------------------------------------------------------------------------
/programming/two-pointers/intersection-of-sorted-arrays.md:
--------------------------------------------------------------------------------
1 | # Intersection Of Sorted Arrays
2 |
3 | https://www.interviewbit.com/problems/intersection-of-sorted-arrays
4 |
5 |
6 | Intersection Of Sorted Arrays
7 | Find the intersection of two sorted arrays.
8 | OR in other words,
9 | Given 2 sorted arrays, find all the elements which occur in both the arrays.
10 | ## Solution
11 |
12 | ```cpp
13 | vector