├── .DS_Store ├── .vscode ├── c_cpp_properties.json └── settings.json ├── CONTRIBUTING.md ├── Cpp ├── .DS_Store ├── 0002-Add_two_numbers │ ├── problem.md │ └── solution.cpp ├── 0004-median-of-two-sorted-array │ ├── problem.md │ └── solution.cpp ├── 0014-longest-common-prefix │ ├── problem.md │ └── solution.cpp ├── 0022-generate-parentheses │ ├── problem.md │ └── solution.cpp ├── 005 Longest Palindromic Substring │ ├── problem.md │ └── solution.cpp ├── 0050-pow(x n) │ ├── problem.md │ └── solution.cpp ├── 0051-N-Queen-I │ ├── problem.md │ └── solution.cpp ├── 0052-N-Queen-II │ ├── problem.md │ └── solution.cpp ├── 0078-subsets │ ├── problem.md │ └── solution.cpp ├── 0090-subsets-II │ ├── problem.md │ └── solution.cpp ├── 0136-Single-Number │ ├── Problem.md │ └── Solution.cpp ├── 0138-copy-list-with-random-pointer │ ├── problem.md │ └── solution.cpp ├── 0213-house-robber-II │ ├── problem.md │ └── solution.cpp ├── 023-Merge-k-Sorted-Lists │ ├── problem.md │ └── solution.cpp ├── 0297-find-the-duplicate-number │ ├── problem.md │ └── solution.cpp ├── 0546-remove-boxes │ ├── problem.md │ ├── solution-2.cpp │ └── solution.cpp ├── 0844-backspace-string-compare │ ├── problem.md │ └── solution.cpp ├── 0896-monotonic-array │ ├── problem.md │ └── solution.cpp ├── 102_Binary Tree Level Order Traversal │ ├── problem.md │ └── solution.cpp ├── 103. Binary Tree Zigzag Level Order Traversal │ ├── problem.md │ └── solution.cpp ├── 1106 - Parsing A Boolean Expression │ ├── problem.md │ └── solution.cpp ├── 128-logest-consecutive-sequence │ ├── problem.md │ ├── solution.cpp │ └── solution2.cpp ├── 1282-group-the-people-given-the-group-size-they-belong-to │ ├── problem.md │ └── solution.cpp ├── 13-roman to integer │ ├── problem.md │ └── solution.cpp ├── 1319-Number-of-Operations-to-Make-Network-Connected │ ├── problem.md │ └── solution.cpp ├── 1539-kth-missing-positive-number │ ├── problem.md │ └── solution.cpp ├── 1813-sentence-similarity-III │ ├── problem.md │ └── solution.cpp ├── 189-rotate-array │ ├── problem.md │ ├── solution1.cpp │ └── solution2.cpp ├── 1903-largest-odd-number-in-string │ ├── problem.md │ └── solution.cpp ├── 198-House-Robber │ ├── problem.md │ └── solution.cpp ├── 216_CombinationSum_III.cpp │ ├── problem.md │ └── solution.cpp ├── 221-Maximal-Square │ ├── problem.md │ └── solution.cpp ├── 229-majority-element-II │ ├── problem.md │ └── solution.cpp ├── 2641. Cousins in Binary Tree II │ ├── problem.md │ └── solution.cpp ├── 2696-minimum-string-length-after-removing-substrings │ ├── problem.md │ └── solution.cpp ├── 274-H-Index │ ├── problem.md │ └── solution.cpp ├── 2938-separate-white-black-balls │ ├── problem.md │ └── solution.cpp ├── 3244-Shortest Distance after Road Addition Q-II │ ├── Screenshot 2024-10-02 at 1.08.38 PM.png │ ├── Solution.cpp │ └── problem.md ├── 33_Search in Rotated Sorted Array │ ├── problem.md │ └── solution.cpp ├── 34. Find First and Last Position of Element in Sorted Array │ ├── problem.md │ └── solution.cpp ├── 347-Top K frequent Elements │ ├── problem.md │ └── solutioon.cpp ├── 3Sum │ ├── problem.md │ └── solution.cpp ├── 410-split-array-largest-sum │ ├── problem.md │ └── solution.cpp ├── 473-Matchsticks-to-Square │ ├── problem.md │ └── solution.cpp ├── 48. Rotate Image │ ├── problem.md │ └── solution.cpp ├── 4Sum │ ├── problem.md │ └── solution.cpp ├── 560-subarray-sum-equals-k │ ├── problem.md │ └── solution.cpp ├── 632.smallest-range-covering-elements-from-k-lists │ ├── problem.md │ └── solution.cpp ├── 706-design-hashmap │ ├── problem.md │ └── solution.cpp ├── 744-find-smallest-letter-greater-than-target │ ├── problem.md │ └── solution.cpp ├── 76-Minimum Window Substring │ ├── problem.md │ └── solution.cpp ├── 785-Is Graph Bipartite │ ├── problem.md │ └── solution.cpp ├── 80_Remove_duplicates_from_sorted_array_II │ ├── problem.md │ ├── solution1.cpp │ └── solution2.cpp ├── 834-Sum-of-Distance-in-Tree │ ├── problem.md │ └── solution.cpp ├── 847. Shortest Path Visiting All Nodes │ ├── Screenshot 2024-10-02 at 12.42.30 PM.png │ ├── problem.md │ └── solution.cpp ├── 987. Vertical Order Traversal of a Binary Tree │ ├── problem.md │ └── solution.cpp ├── 99_Recover Binary Search Tree │ ├── problem.md │ └── solution.cpp ├── Air-Quality-Index │ ├── problem.md │ └── solution.cpp ├── Another permutation problem │ ├── problem.md │ └── solution.cpp ├── Best Time to buy and sell stock │ ├── problem.md │ └── solution.cpp ├── Bob the Destroyer │ ├── problem.md │ └── solution.cpp ├── Chips-on-the-board │ ├── problem.md │ └── solution.cpp ├── Count inversion │ ├── problem.md │ └── solution.cpp ├── Dardos │ ├── problem.md │ └── solution.cpp ├── Diameter of a tree │ ├── problem.md │ └── solution.cpp ├── Different patterns in C++ │ ├── Problem.md │ └── Solution.cpp ├── Dota2-senate │ ├── problem.md │ └── solution.cpp ├── Euler │ ├── problem.md │ └── solution.cpp ├── Even-Coefficients │ ├── problem.md │ └── solution.cpp ├── Exams │ ├── problem.md │ └── solution.cpp ├── Fire Again │ ├── Problem.md │ └── solution.cpp ├── First_and_Last_Position_of_Element_in_Array │ ├── problem.md │ └── solution.cpp ├── Implement_Trie_(Prefix_Tree) │ ├── problem.md │ └── solution.cpp ├── Josephus_prob │ ├── problem.md │ └── solution.cpp ├── Kitayuta's Colorful Graph │ ├── Problem.md │ └── solution.cpp ├── LFU_Cache │ ├── problem.md │ └── solution.cpp ├── LRU_Cache │ ├── problem.md │ └── solution.cpp ├── Longest Common Subsequence │ ├── problem.md │ └── solution.cpp ├── Longest Unequal Adjacent Groups Subsequence I │ ├── problem.md │ └── solution.cpp ├── Longest repeating character replacement │ ├── problem.md │ └── solution.cpp ├── Magical calendar │ ├── problem.md │ └── solution.cpp ├── Max-sum-path-in-two-arrays │ ├── problem.md │ └── solution.cpp ├── Maximum_XOR_With_an_Element_From_Array │ ├── problem.md │ └── solution.cpp ├── Mex-Tree │ ├── problem.md │ └── solution.cpp ├── Number Theory Love │ ├── problem.md │ └── solution.cpp ├── Number of Enclaves │ ├── problem.md │ └── solution.cpp ├── Painter's Partition Problem │ ├── Problem.md │ └── solution.cpp ├── Pairs with Given Sum │ ├── problem.md │ └── solution.cpp ├── Range_Module │ ├── problem.md │ └── solution.cpp ├── Rotate-an-array-by-K │ ├── problem.md │ ├── solution.cpp │ └── solution2.cpp ├── Rudolf and the Another Competition │ ├── problem.md │ └── solution.cpp ├── Sorting Algorithm-Program │ ├── Problem.md │ └── Solution.cpp ├── Top K Frequent Elements │ ├── problem.md │ └── solution.cpp ├── Two-Sum │ ├── problem.md │ └── solution.cpp ├── Unique Path │ ├── problem.md │ └── solution.cpp ├── Valera and Elections │ ├── Problem.md │ └── solution.cpp ├── Witua-and-maths │ ├── problem.md │ └── solution.cpp ├── add-binary │ ├── problem.md │ └── solution.cpp ├── angry-professor │ ├── problem.md │ └── solution.cpp ├── append-and-delete │ ├── problem.md │ └── solution.cpp ├── apple-orange │ ├── problem.md │ └── solution.cpp ├── beautiful-days-at-the-movies │ ├── problem.md │ └── solution.cpp ├── between-two-sets │ ├── problem.md │ └── solution.cpp ├── bill-division │ ├── problem.md │ └── solution.cpp ├── binary-tree-maximum-path-sum │ ├── problem.md │ └── solution.cpp ├── birthday-bar │ ├── problem.md │ └── solution.cpp ├── birthday-cake-candles │ ├── problem.md │ └── solution.cpp ├── breaking-the-records │ ├── problem.md │ └── solution.cpp ├── buy-sell-stock │ ├── problem.md │ └── solution.cpp ├── can-place-flowers │ ├── problem.md │ └── solution.cpp ├── cats-and-a-mouse │ ├── problem.md │ └── solution.cpp ├── circular-array-rotation │ ├── problem.md │ └── solution.cpp ├── climbing-stairs │ ├── problem.md │ └── solution.cpp ├── climbing-the-leaderboard │ ├── problem.md │ └── solution.cpp ├── common-divisor │ ├── problem.md │ └── solution.cpp ├── compare-triplets │ ├── problem.md │ └── solution.cpp ├── container-with-most-water │ ├── problem.md │ └── solution.cpp ├── convert-sorted-array-to-binary-search-tree │ ├── problem.md │ └── solution.cpp ├── counting-valleys │ ├── problem.md │ └── solution.cpp ├── cut-the-sticks │ ├── problem.md │ └── solution.cpp ├── day-of-the-programmer │ ├── problem.md │ └── solution.cpp ├── designer-pdf-viewer │ ├── problem.md │ └── solution.cpp ├── diagonal-difference │ ├── problem.md │ └── solution.cpp ├── divisible-sum-pairs │ ├── problem.md │ └── solution.cpp ├── drawing-book │ ├── problem.md │ └── solution.cpp ├── dungeon-game │ ├── problem.md │ └── solution.cpp ├── edit-distance │ ├── problem.md │ ├── solution.cpp │ └── solution2.cpp ├── electronics-shop │ ├── problem.md │ └── solution.cpp ├── equality-in-a-array │ ├── problem.md │ └── solution.cpp ├── find-digits │ ├── problem.md │ └── solution.cpp ├── find-max-average │ ├── problem.md │ └── solution.cpp ├── find-the-duplicate │ ├── problem.md │ └── solution.cpp ├── going-to-cinema │ ├── problem.md │ └── solution.cpp ├── goldbach_conjecture │ ├── problem.md │ └── solution.cpp ├── grading-students │ ├── problem.md │ └── solution.cpp ├── group-anagrams │ ├── problem.md │ └── solution.cpp ├── is-subsequence │ ├── problem.md │ └── solution.cpp ├── jumping-on-the-clouds │ ├── problem-2.md │ ├── problem.md │ ├── solution-2.cpp │ └── solution.cpp ├── k-dice Ways │ ├── problem.md │ └── solution.cpp ├── kids-with-the-greatest-number-of-candies │ ├── problem.md │ └── solution.cpp ├── kokoEatingBananas │ ├── problem.md │ └── solution.cpp ├── largest-rectangle-in-histogram │ ├── problem.md │ └── solution.cpp ├── length-of-last-word │ ├── problem.md │ └── solution.cpp ├── library-fine │ ├── problem.md │ └── solution.cpp ├── longest-common-prefix │ ├── problem.md │ └── solution.cpp ├── longest-consecutive-sequence │ ├── problem.md │ └── solution.cpp ├── longest-valid-parentheses │ ├── problem.md │ └── solution.cpp ├── magic-square │ ├── problem.md │ └── solution.cpp ├── majority-element │ ├── problem.md │ └── solution.cpp ├── maximum-product-subarray │ ├── problem.md │ └── solution.cpp ├── maximum-subarray │ ├── problem.md │ └── solution.cpp ├── merge-sorted-array │ ├── problem.md │ └── solution.cpp ├── merge-strings │ ├── problem.md │ └── solution.cpp ├── migratory-birds │ ├── problem.md │ └── solution.cpp ├── min-max-sum │ ├── problem.md │ ├── solution-2.cpp │ └── solution.cpp ├── move-zeros │ ├── problem.md │ └── solution.cpp ├── next-permutation │ ├── problem.md │ └── solution.cpp ├── number-line-jumps │ ├── problem.md │ └── solution.cpp ├── palindrome-number │ ├── problem.md │ └── solution.cpp ├── pascals-triangle │ ├── problem.md │ └── solution.cpp ├── picking-numbers │ ├── problem.md │ └── solution.cpp ├── plus-minus │ ├── problem.md │ └── solution.cpp ├── plus-one │ ├── problem.md │ └── solution.cpp ├── postfix-evaluation │ ├── problem.md │ └── solution.cpp ├── product_of_numbers │ ├── problem.md │ └── solution.cpp ├── pythagorean theorem │ ├── problem.md │ └── solution.cpp ├── rearrange-substrings │ ├── problem.md │ └── solution.cpp ├── remove-element │ ├── problem.md │ └── solution.cpp ├── remove-loop-in-linked-list │ ├── problem.md │ └── solution.cpp ├── repeated-strings │ ├── problem.md │ └── solution.cpp ├── reverse-integer │ ├── problem.md │ └── solution.cpp ├── reverse-vowels │ ├── problem.md │ └── solution.cpp ├── reverse-words-in-a-string │ ├── problem.md │ └── solution.cpp ├── roman-numbers │ ├── problem.md │ └── solution.cpp ├── sales-by-match │ ├── problem.md │ └── solution.cpp ├── save-the-prisoner │ ├── problem.md │ └── solution.cpp ├── search-2d-matrix-(ii) │ ├── problem.md │ ├── solution-1.cpp │ └── solution-2.cpp ├── search-insert-position │ ├── problem.md │ └── solution.cpp ├── sequence-equation │ ├── problem.md │ └── solution.cpp ├── sherlock-and-squares │ ├── problem.md │ └── solution.cpp ├── single-number │ ├── problem.md │ └── solution.cpp ├── spiral_matrix │ ├── problem.md │ └── solution.cpp ├── sqrt │ ├── problem.md │ └── solution.cpp ├── staircase │ ├── problem.md │ └── solution.cpp ├── sum_of_list │ ├── problem.md │ └── solution.cpp ├── the-hurdle-race │ ├── problem.md │ └── solution.cpp ├── time-conversion │ ├── problem.md │ └── solution.cpp ├── trapping-rain-water-cpp │ ├── problem.md │ └── solution.cpp ├── triangular_number_sequence │ ├── problem.md │ └── solution.cpp ├── utopian-tree │ ├── problem.md │ └── solution.cpp ├── valid-palindrome │ ├── problem.md │ └── solution.cpp ├── valid-parenthesis │ ├── problem.md │ └── solution.cpp ├── valid-sudoku │ ├── problem.md │ └── solution.cpp ├── validate-binary-search-tree │ ├── problem.md │ └── solution.cpp ├── very-big-sum │ ├── problem.md │ └── solution.cpp ├── viral-advertising │ ├── problem.md │ └── solution.cpp └── winning-sequence │ ├── problem.md │ └── solution.cpp ├── Java ├── Arrangingcoin │ ├── problem.md │ └── solution.java ├── Construct Binary Search Tree from Preorder Traversal │ ├── Problem.md │ └── Solution.java ├── Count of Smaller Numbers After Self │ ├── problem.md │ └── solution.java ├── Find the kth Bit in the nth Binary String │ ├── problem.md │ └── solution.java ├── Group Anagrams │ ├── Solution.java │ └── problem.md ├── Horses │ ├── problem.md │ └── solution.java ├── Longest Happy String │ ├── problem.md │ └── solution.java ├── Longest Square Streak in Array │ ├── problem.md │ └── solution.java ├── Longest_common_prefix │ ├── problem.md │ └── solution.java ├── Minimum Add to Make Parenthesis Valid │ └── solution.java ├── Minimum Number of Swaps to make the String Balanced │ ├── problem.md │ └── solution.java ├── Remove Subfolders from File System │ ├── problem.md │ └── solution.java ├── Separate Black and White Balls │ ├── problem.md │ └── solution.java ├── String to integer │ ├── problem.md │ └── solution.java ├── Valid_Sudoko_problem │ ├── problem.md │ └── solution.java └── fmPositive │ ├── problem.md │ └── solution.java ├── Js ├── 20-valid-parentheses │ ├── problem.md │ └── solution.js ├── 2605-Counter │ ├── problem.md │ └── solution.js ├── EventEmitter │ ├── problem.md │ └── solution.js └── Join_2_arrays_by_Id │ ├── problem.md │ └── solution.js ├── Py ├── 0002.Add_Two_numbers │ ├── problem.md │ └── solution.py ├── 0004-median-of-two-sorted-array │ ├── problem.md │ └── solution.py ├── 0004. Median of Two Sorted Arrays │ ├── problem.md │ └── solution.py ├── 0007.Reverse_Integer │ ├── problem.md │ └── solution.py ├── 0013-Roman_to_Integer │ ├── problem.md │ └── solution.py ├── 0014-longest-common-prefix │ ├── problem.md │ └── solution.py ├── 0015-3sum │ ├── problem.md │ └── solution.py ├── 0016-3Sum-Closest │ ├── problem.md │ └── solution.py ├── 0017-Letter-Combinations-of-a-Phone-Number │ ├── problem.md │ └── solution.py ├── 0018-4Sum │ ├── problem.md │ └── solution.py ├── 0022-generate-parenthesis │ ├── problem.md │ └── solution.py ├── 0025-reverse-nodes-in-k-group │ ├── problem.md │ └── solution.py ├── 0026 Remove Duplicate from Sorted Array │ ├── Solution.py │ └── problem.md ├── 0033-search-in-rotated-sorted-array │ ├── problem.md │ └── solution.py ├── 0042-trapping-rain-water │ ├── problem.md │ └── solution.py ├── 0050-pow(x n) │ ├── problem.md │ └── solution.py ├── 0061-rotate-list │ ├── problem.md │ └── solution.py ├── 0078-subsets │ ├── problem.md │ └── solution.py ├── 0090-subsets-II │ ├── problem.md │ └── solution.py ├── 0128-longest-consecutive-sequence │ ├── problem.md │ ├── solution.py │ └── solution2.py ├── 0138-copy-list-wit-random-pointer │ ├── problem.md │ └── solution.py ├── 0141. Linked List Cycle │ ├── problem.md │ └── solution.py ├── 0148-sort-list │ ├── porblem.md │ └── solution.py ├── 0174-dungeon-game │ ├── problem.md │ └── solution.py ├── 0204-Count-Primes │ ├── problem.md │ └── solution.py ├── 0206-reverse-linked-list │ ├── problem.md │ └── solution.py ├── 0229-majority-element-II │ ├── problem.md │ └── solution.py ├── 0232. Implement Queue using Stack │ ├── problem.md │ └── solution.py ├── 0234-palindrome-linked-list │ ├── problem.md │ └── solution.py ├── 0273-Integer-to-English-Words │ ├── problem.md │ └── solution.py ├── 0342.Power_of_Four │ ├── problem.md │ └── solution.py ├── 0404-sum-of-left-leaves │ ├── problem.md │ └── solution.py ├── 0420-strong-password-checker │ ├── problem.md │ └── solution.py ├── 0560-subarray-sum-equal-k │ ├── problem.md │ └── solution.py ├── 0566-reshape-the-matrix │ ├── problem.md │ └── solution.py ├── 0876-middle-of-the-linked-list │ ├── problem.md │ └── solution.py ├── 15305-new-year-chaos │ ├── problem.md │ └── solution.py ├── 1539-kth-missing-positive-number │ ├── problem.md │ └── solution.py ├── 189-rotate-array │ ├── problem.md │ ├── solution1.py │ └── solution2.py ├── 2301-manasa-and-factorials │ ├── problem.md │ └── solution.py ├── 2405-optimal-partition-of-string │ ├── problem.md │ └── solution.py ├── 24548-repeated-string │ ├── problem.md │ └── solution.py ├── 2536-sherlock-and-divisors │ ├── problem.md │ └── solution.py ├── 410-split-array-largest-sum │ ├── problem.md │ └── solution.py ├── 5529-fliping-bits │ ├── problem.md │ └── solution.py ├── 593_Valid_Square │ ├── problem.md │ └── solution.py └── 645-Set-Mismatch │ ├── problem.md │ └── solution.py ├── README.md └── images ├── PascalTriangleAnimated2.gif ├── apple-orange.png ├── book-1.png ├── books.png ├── container-with-most-water.jpg ├── designer-pdf-viewer.png ├── logo.png └── sudoku-board.png /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/.DS_Store -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "windows-gcc-x86", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "compilerPath": "C:/MinGW/bin/gcc.exe", 9 | "cStandard": "${default}", 10 | "cppStandard": "${default}", 11 | "intelliSenseMode": "windows-gcc-x86", 12 | "compilerArgs": [ 13 | "" 14 | ] 15 | } 16 | ], 17 | "version": 4 18 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "iostream": "cpp", 4 | "vector": "cpp", 5 | "*.tcc": "cpp", 6 | "forward_list": "cpp", 7 | "list": "cpp", 8 | "ostream": "cpp", 9 | "functional": "cpp" 10 | } 11 | } -------------------------------------------------------------------------------- /Cpp/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/Cpp/.DS_Store -------------------------------------------------------------------------------- /Cpp/0002-Add_two_numbers/problem.md: -------------------------------------------------------------------------------- 1 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. 2 | 3 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | 10 | Input: l1 = [2,4,3], l2 = [5,6,4] 11 | Output: [7,0,8] 12 | Explanation: 342 + 465 = 807. 13 | Example 2: 14 | 15 | Input: l1 = [0], l2 = [0] 16 | Output: [0] 17 | Example 3: 18 | 19 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] 20 | Output: [8,9,9,9,0,0,0,1] 21 | 22 | 23 | Constraints: 24 | 25 | The number of nodes in each linked list is in the range [1, 100]. 26 | 0 <= Node.val <= 9 27 | It is guaranteed that the list represents a number that does not have leading zeros. 28 | -------------------------------------------------------------------------------- /Cpp/0002-Add_two_numbers/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 4 | int carry = 0; 5 | ListNode* head = new ListNode(0); // Dummy node to simplify code 6 | ListNode* curr = head; 7 | 8 | while (l1 || l2) { 9 | int val1 = l1 ? l1->val : 0; 10 | int val2 = l2 ? l2->val : 0; 11 | 12 | int total = val1 + val2 + carry; 13 | curr->next = new ListNode(total % 10); 14 | carry = total / 10; 15 | 16 | if (l1) l1 = l1->next; 17 | if (l2) l2 = l2->next; 18 | curr = curr->next; 19 | } 20 | 21 | if (carry > 0) { 22 | curr->next = new ListNode(carry); 23 | } 24 | 25 | return head->next; // Skip the dummy node 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Cpp/0014-longest-common-prefix/problem.md: -------------------------------------------------------------------------------- 1 |

14. Longest Common Prefix

2 | 3 |

Easy

4 | 5 |
6 | 7 |

Write a function to find the longest common prefix string amongst an array of strings.

8 | 9 |

If there is no common prefix, return an empty string "".

10 | 11 |

 

12 |

Example 1:

13 | 14 |
Input: strs = ["flower","flow","flight"]
15 | Output: "fl"
16 | 
17 | 18 |

Example 2:

19 | 20 |
Input: strs = ["dog","racecar","car"]
21 | Output: ""
22 | Explanation: There is no common prefix among the input strings.
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 | 33 |
34 | -------------------------------------------------------------------------------- /Cpp/0014-longest-common-prefix/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string longestCommonPrefix(vector &strs) 5 | { 6 | // Sort the vector of strings 7 | sort(strs.begin(), strs.end()); 8 | 9 | // Initialize the answer string and get the first and last strings from the sorted vector 10 | string ans = "", fst = strs[0], lst = strs[strs.size() - 1]; 11 | 12 | // Iterate through the characters of the first and last strings 13 | for (int i = 0; i < min(fst.size(), lst.size()); i++) 14 | { 15 | // If the characters at the current position are the same, add to the answer string 16 | if (fst[i] == lst[i]) 17 | { 18 | ans += fst[i]; 19 | } 20 | // If not, break out of the loop as this is where the common prefix ends 21 | else 22 | { 23 | break; 24 | } 25 | } 26 | 27 | // Return the computed common prefix 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Cpp/0022-generate-parentheses/problem.md: -------------------------------------------------------------------------------- 1 |

22. Generate Parentheses

2 | 3 |

Medium

4 | 5 |
6 |

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

7 | 8 |

 

9 |

Example 1:

10 |
Input: n = 3
11 | Output: ["((()))","(()())","(())()","()(())","()()()"]
12 | 

Example 2:

13 |
Input: n = 1
14 | Output: ["()"]
15 | 
16 |

 

17 |

Constraints:

18 | 19 | 22 |
23 | -------------------------------------------------------------------------------- /Cpp/005 Longest Palindromic Substring/problem.md: -------------------------------------------------------------------------------- 1 |

Longest Palindromic Substring

2 |

Status: Solved

3 |

Difficulty: Medium

4 |

Topics: Dynamic Programming, Strings

5 |

Companies: Multiple

6 |

Problem Statement: Given a string s, return the longest palindromic substring in s.

7 | 8 |

Example 1:

9 |

Input: s = "babad"

10 |

Output: "bab"

11 |

Explanation: "aba" is also a valid answer.

12 | 13 |

Example 2:

14 |

Input: s = "cbbd"

15 |

Output: "bb"

16 | 17 |

Constraints:

18 | -------------------------------------------------------------------------------- /Cpp/005 Longest Palindromic Substring/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solutio { 2 | public: 3 | // Function to check if a substring of 'str' from index 's' to 'e' is a palindrome 4 | bool isPalindrome(string &str, int s, int e) { 5 | e -= 1; 6 | while (s < e) { 7 | if (str[s] != str[e]) 8 | return false; 9 | s++; 10 | e--; 11 | } 12 | return true; 13 | } 14 | 15 | // Function to find the longest palindromic substring in the given string 's' 16 | string longestPalindrome(string s) { 17 | for (int i = s.length(); i > 0; i--) { 18 | for (int j = 0; j <= s.length() - i; j++) { 19 | if (isPalindrome(s, j, j + i)) { 20 | return s.substr(j, i); 21 | } 22 | } 23 | } 24 | return ""; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Cpp/0050-pow(x n)/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, int n) { 4 | // Initialize the result variable to 1 5 | double ans = 1; 6 | 7 | // Convert n to a long long to handle the edge case when n is INT_MIN 8 | long long m = n; 9 | 10 | // If n is negative, make it positive and keep track of it 11 | if (n < 0) { 12 | m = (-1) * m; 13 | } 14 | 15 | // Main loop for exponentiation 16 | while (m > 0) { 17 | // If m is odd, multiply the result by x and decrement m by 1 18 | if (m % 2 == 1) { 19 | ans = ans * x; 20 | m -= 1; 21 | } 22 | // If m is even, square x and divide m by 2 23 | else { 24 | x = x * x; 25 | m = m / 2; 26 | } 27 | } 28 | 29 | // If n was originally negative, return the reciprocal of ans, otherwise, return ans 30 | return (n < 0) ? 1 / ans : ans; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Cpp/0051-N-Queen-I/problem.md: -------------------------------------------------------------------------------- 1 | # N-Queens 2 | 3 | ## Problem Description 4 | The **N-Queens** puzzle requires placing `n` queens on an `n x n` chessboard such that no two queens threaten each other. A queen can attack any piece in the same row, column, or diagonal. 5 | 6 | Given an integer `n`, the task is to find all distinct solutions to the N-Queens puzzle. Each solution should be represented as a distinct board configuration where `'Q'` denotes a queen, and `'.'` denotes an empty square. 7 | 8 | ## Objective 9 | Return all possible configurations of the N-Queens puzzle in any order, where each configuration is a list of strings representing the chessboard. 10 | 11 | --- 12 | 13 | ### Constraints 14 | - `1 <= n <= 9` 15 | 16 | ### Example 17 | **Input** 18 | ```plaintext 19 | n = 4 20 | ``` 21 | 22 | 23 | **Output** 24 | ```plaintext 25 | [[".Q..","...Q","Q...","..Q."], 26 | ["..Q.","Q...","...Q",".Q.."]] 27 | ``` 28 | -------------------------------------------------------------------------------- /Cpp/0052-N-Queen-II/problem.md: -------------------------------------------------------------------------------- 1 | # N-Queens II 2 | 3 | ## Problem Description 4 | The **N-Queens puzzle** is the problem of placing `n` queens on an `n x n` chessboard so that no two queens can attack each other (no same row, column, or diagonal). This variation of the problem, N-Queens II, requires counting the number of distinct solutions rather than returning each configuration. 5 | 6 | Given an integer `n`, return the number of unique ways to arrange the queens on the chessboard. 7 | 8 | ## Objective 9 | Return the count of all valid configurations for the N-Queens puzzle, where each configuration ensures that no two queens attack each other. 10 | 11 | --- 12 | 13 | ### Constraints 14 | - `1 <= n <= 9` 15 | 16 | ### Examples 17 | 18 | **Example 1** 19 | 20 | **Input** 21 | ```plaintext 22 | n = 4 23 | ``` 24 | 25 | **Output** 26 | ```plaintext 27 | 2 28 | ``` 29 | 30 | **Example 2** 31 | 32 | **Input** 33 | ```plaintext 34 | n = 1 35 | ``` 36 | 37 | **Output** 38 | ```plaintext 39 | 1 40 | ``` -------------------------------------------------------------------------------- /Cpp/0136-Single-Number/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int singleNumber(vector &nums) 5 | { 6 | // Initialize a variable `xorr` to 0, which will be used to store the XOR result. 7 | int xorr = 0; 8 | 9 | // Iterate through each element in the array `nums`. 10 | for (int i = 0; i < nums.size(); i++) 11 | { 12 | // Apply XOR operation between `xorr` and the current element `nums[i]`. 13 | // This will cancel out all elements that appear twice and leave only the single element. 14 | xorr = xorr ^ nums[i]; 15 | } 16 | 17 | // Return the remaining element, which is the single element that does not have a duplicate. 18 | return xorr; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Cpp/023-Merge-k-Sorted-Lists/problem.md: -------------------------------------------------------------------------------- 1 | # Merge k Sorted Lists 2 | 3 | ## Problem Statement 4 | 5 | You are given an array of `k` linked-lists, each linked-list is sorted in ascending order. 6 | 7 | Merge all the linked-lists into one sorted linked-list and return it. 8 | 9 | ## Example 10 | 11 | **Input:** 12 | ```plaintext 13 | [ 14 | 1 -> 4 -> 5, 15 | 1 -> 3 -> 4, 16 | 2 -> 6 17 | ] 18 | ``` 19 | 20 | **Output:** 21 | ``` 22 | 1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6 23 | ``` 24 | 25 | ## Constraints 26 | 27 | - `k == lists.length` 28 | - `0 <= k <= 10^4` 29 | - `0 <= lists[i].length <= 500` 30 | - `-10^4 <= lists[i][j] <= 10^4` 31 | - `lists[i]` is sorted in ascending order. 32 | - The sum of `lists[i].length` will not exceed `10^4`. 33 | -------------------------------------------------------------------------------- /Cpp/0297-find-the-duplicate-number/solution.cpp: -------------------------------------------------------------------------------- 1 | /**Solution with 2 | * Time Complexity: O(N) 3 | * Space Complexity: O(N)*/ 4 | 5 | class Solution { 6 | public: 7 | int findDuplicate(vector& nums) { 8 | //Create a STL hashmap of (int,bool), we will use the logic that 9 | //while traversing the array if an element is already visited i.e. value is true then it is the repeated element 10 | //STL set can also be used 11 | unordered_map mp; 12 | 13 | //traverse the vector 14 | for(int val:nums){ 15 | //we assign true to an element if it is not visited before 16 | if(mp[val]==false) mp[val]=true; 17 | 18 | //return the element if the element is already visited 19 | else return val; 20 | } 21 | return 0; 22 | } 23 | }; -------------------------------------------------------------------------------- /Cpp/0546-remove-boxes/problem.md: -------------------------------------------------------------------------------- 1 | # Problem: Remove Boxes 2 | 3 | ## Category: Hard 4 | 5 | 6 | ## Description 7 | You are given several `boxes` with different colors represented by different positive numbers. 8 | 9 | You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points. 10 | 11 | Return the `maximum points` you can get. 12 | 13 | ## Example 1 14 | ### Input: boxes = [1,3,2,2,2,3,4,3,1] 15 | ### Output: 23 16 | ### Explanation: 17 | - [1, 3, 2, 2, 2, 3, 4, 3, 1] 18 | - [1, 3, 3, 4, 3, 1] (3*3=9 points) 19 | - [1, 3, 3, 3, 1] (1*1=1 points) 20 | - [1, 1] (3*3=9 points) 21 | - [] (2*2=4 points) 22 | 23 | 24 | ## Example 2 25 | ### Input: boxes = [1,1,1] 26 | ### Output: 9 27 | 28 | ## Example 3 29 | ### Input: boxes = [1] 30 | ### Output: 1 31 | 32 | 33 | ## Constraints 34 | - `1 <= boxes.length <= 100` 35 | - `1 <= boxes[i] <= 100` 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Cpp/0546-remove-boxes/solution-2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | vector>> dp; 3 | public: 4 | int removeBoxes(vector& boxes) { 5 | int n = boxes.size(); 6 | dp.resize(n+1, vector>(n+1, vector(n+1, -1))); 7 | 8 | return solve(boxes, 0, n-1, 0); 9 | } 10 | 11 | int solve(vector &boxes, int i, int j, int cnt) { 12 | if(i > j) return 0; 13 | 14 | if(dp[i][j][cnt] != -1) return dp[i][j][cnt]; 15 | 16 | int i0 = i, cnt0 = cnt; 17 | 18 | while(i + 1 <= j && boxes[i] == boxes[i+1]) i++, cnt++; 19 | 20 | int ans = (cnt+1) * (cnt+1) + solve(boxes, i+1, j, 0); 21 | 22 | for(int k=i+1; k<=j; k++) { 23 | if(boxes[k] == boxes[i]) { 24 | ans = max(ans, solve(boxes, i+1, k-1, 0) + solve(boxes, k, j, cnt+1)); 25 | } 26 | } 27 | return dp[i0][j][cnt0] = ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Cpp/0896-monotonic-array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMonotonic(vector& nums) { 4 | bool increse = true; 5 | bool dicr = true; 6 | for (int i = 0; i < nums.size() - 1; i++) 7 | { 8 | if (nums[i] < nums[i + 1]) 9 | dicr = false; 10 | if (nums [i] > nums[i + 1]) 11 | increse = false; 12 | } 13 | return increse || dicr; 14 | } 15 | }; -------------------------------------------------------------------------------- /Cpp/102_Binary Tree Level Order Traversal/problem.md: -------------------------------------------------------------------------------- 1 |

📌 102. Binary Tree Level Order Traversal

2 | 3 |

Medium

4 | 5 | Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level) 6 | 7 |

 

8 | 9 | Example 1: 10 |
Input: root = [3,9,20,null,null,15,7]
11 | Output: [[3],[9,20],[15,7]]
12 | 
13 | 14 | 15 | Example 2: 16 |
Input: root = [1]
17 | Output: [[1]]
18 | 
19 | 20 | 21 | Example 3: 22 |
Input: root = []
23 | Output: []
24 | 
25 | 26 |

 

27 | 28 | Constraints: 29 | 30 | - The number of nodes in the tree is in the range [0, 2000]. 31 | - -1000 <= Node.val <= 1000 -------------------------------------------------------------------------------- /Cpp/103. Binary Tree Zigzag Level Order Traversal/problem.md: -------------------------------------------------------------------------------- 1 | Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). -------------------------------------------------------------------------------- /Cpp/1106 - Parsing A Boolean Expression/problem.md: -------------------------------------------------------------------------------- 1 | A boolean expression is an expression that evaluates to either true or false, and it can have the following forms: 2 | 3 | 1. `'t'`: evaluates to true. 4 | 2. `'f'`: evaluates to false. 5 | 3. `'!(subExpr)'`: evaluates to the logical NOT of the inner expression `subExpr`. 6 | 4. `'&(subExpr1, subExpr2, ..., subExprn)'`: evaluates to the logical AND of the inner expressions `subExpr1, subExpr2, ..., subExprn`, where `n >= 1`. 7 | 5. `'|(subExpr1, subExpr2, ..., subExprn)'`: evaluates to the logical OR of the inner expressions `subExpr1, subExpr2, ..., subExprn`, where `n >= 1`. 8 | 9 | Given a string `expression` that represents a boolean expression, return its evaluation. It is guaranteed that the expression is valid and follows the rules described above. 10 | 11 | --- 12 | -------------------------------------------------------------------------------- /Cpp/13-roman to integer/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int romanToInt(string s) { 4 | int sum=0; 5 | unordered_mapt; 6 | // The map is used to store the value of each Roman later 7 | t['I']=1; 8 | t['V']=5; 9 | t['X']=10; 10 | t['L']=50; 11 | t['C']=100; 12 | t['D']=500; 13 | t['M']=1000; 14 | for(int i=0;i& nums, int k) { 6 | // Get the size of the 'nums' vector 7 | int n = nums.size(); 8 | 9 | // Create a new vector 'ans' to store the rotated values 10 | vector ans(n); 11 | 12 | // Iterate over the 'nums' vector 13 | for(int i=0; i& nums, int k) { 6 | // Get the size of the 'nums' vector 7 | int n = nums.size(); 8 | 9 | // Adjust 'k' to handle cases where 'k' is larger than 'n' 10 | // This ensures the rotation wraps around if 'k' is larger than 'n' 11 | k = k % n; 12 | 13 | // Reverse the first part of the vector (0 to n-k-1) 14 | reverse(nums.begin(), nums.begin() + (n - k)); 15 | 16 | // Reverse the second part of the vector (n-k to n-1) 17 | reverse(nums.begin() + (n - k), nums.end()); 18 | 19 | // Reverse the entire vector 20 | reverse(nums.begin(), nums.end()); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Cpp/1903-largest-odd-number-in-string/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string largestOddNumber(string num) { 4 | // Get the size of the string 5 | int n = num.size(); 6 | 7 | // Loop backwards through the string 8 | for(int i = n; i >= 0; i--){ 9 | 10 | // Get the char number value of the character at position i 11 | int last = num[i]; 12 | 13 | // Check if the digit at position i is odd 14 | // This is done by converting the character to its integer value and checking the last bit 15 | if((last-'0') & 1){ 16 | 17 | // If odd, return the substring from the start till the odd digit 18 | return num.substr(0, i+1); 19 | } 20 | } 21 | 22 | // If no odd digit is found, return an empty string 23 | return ""; 24 | } 25 | }; -------------------------------------------------------------------------------- /Cpp/221-Maximal-Square/problem.md: -------------------------------------------------------------------------------- 1 | 221. Maximal Square 2 | 3 | Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | 10 | Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] 11 | Output: 4 12 | Example 2: 13 | 14 | 15 | Input: matrix = [["0","1"],["1","0"]] 16 | Output: 1 17 | Example 3: 18 | 19 | Input: matrix = [["0"]] 20 | Output: 0 21 | 22 | 23 | Constraints: 24 | 25 | m == matrix.length 26 | n == matrix[i].length 27 | 1 <= m, n <= 300 28 | matrix[i][j] is '0' or '1'. -------------------------------------------------------------------------------- /Cpp/274-H-Index/problem.md: -------------------------------------------------------------------------------- 1 | ## 276. H - Index 2 | 3 | The H-Index is a metric used to measure the productivity and citation impact of a researcher. Given an array of integers, `citations`, where `citations[i]` represents the number of citations received for the researcher’s `i - th paper`, the goal is to calculate the researcher's H-Index. 4 | 5 | The H-Index is defined as the maximum value of `h` such that the researcher has published at least `h` papers that have each been cited at least `h` times. 6 | 7 | **Input:** `citations = [3,0,6,1,5]` 8 | 9 | **Output:** `3` 10 | 11 | **Explanation:** `[3,0,6,1,5]` means the researcher has 5 papers in total and each of them had received `3, 0, 6, 1, 5` citations respectively. 12 | Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. -------------------------------------------------------------------------------- /Cpp/2938-separate-white-black-balls/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long minimumSteps(string s) { 4 | //Initialise both steps and ones 5 | long long steps=0; 6 | long long ones=0; 7 | //For every character, 8 | for(char c: s) { 9 | //If the character is 1, count it in the ones variable 10 | if(c=='1') { 11 | ones+=1; 12 | } else if(c=='0'&& ones>0) { //else if it a 0 after 1, add it to steps 13 | steps+=ones; 14 | } 15 | } 16 | //Return steps 17 | return steps; 18 | } 19 | }; 20 | 21 | static const auto init = [](){ 22 | ios_base::sync_with_stdio(false); 23 | cin.tie(nullptr); 24 | cout.tie(nullptr); 25 | return 0; 26 | }(); -------------------------------------------------------------------------------- /Cpp/3244-Shortest Distance after Road Addition Q-II/Screenshot 2024-10-02 at 1.08.38 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/Cpp/3244-Shortest Distance after Road Addition Q-II/Screenshot 2024-10-02 at 1.08.38 PM.png -------------------------------------------------------------------------------- /Cpp/3244-Shortest Distance after Road Addition Q-II/problem.md: -------------------------------------------------------------------------------- 1 | # 3244 Shortest Distance after Road Addition Queries - II 2 | 3 | ## Problem Overview 4 | 5 | You are given an integer `n` and a 2D integer array `queries`. 6 | 7 | There are `n` cities numbered from `0` to `n-1`. Initially, there is a road from city `i` to city `i+1` for all `0 <= i < n-1`. 8 | 9 | `queries[i] = [ui, vi]` represents the addition of a new unidirectional road from city `ui` to city `vi`. After each query, you need to find the length of the shortest path from city 0 to city n - 1. 10 | 11 | There are no two queries such that `queries[i][0] < queries[j][0] < queries[i][1]queries[j][1]`. 12 | 13 | **Example 1:** 14 | **Input :** `n` = 5, graph = `[[2,5], [0,2], [0,4]]` 15 | 16 | **Output** = `[3,2,1]` 17 | 18 | **Explanation**: ![alt text]() 19 | 20 | ### Function Signature 21 | ```cpp 22 | class Solution { 23 | public: 24 | vector shortestDistanceAfterQueries(int n, vector>& queries) { 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Cpp/34. Find First and Last Position of Element in Sorted Array/problem.md: -------------------------------------------------------------------------------- 1 | # 34. Find First and Last Position of Element in Sorted Array 2 | 3 | [Problem Link](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/) 4 | 5 | ## Problem Description 6 | Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value. 7 | 8 | If `target` is not found in the array, return `[-1, -1]`. 9 | 10 | You must write an algorithm with `O(log n)` runtime complexity. 11 | 12 | ### Constraints 13 | - `0 <= nums.length <= 10^5` 14 | - `-10^9 <= nums[i] <= 10^9` 15 | - `nums` is a non-decreasing array. 16 | - `-10^9 <= target <= 10^9` 17 | 18 | ## Examples 19 | 20 | ### Example 1: 21 | 22 | Input: nums = [5,7,7,8,8,10], target = 8 23 | 24 | Output: [3,4] 25 | 26 | ### Example 2: 27 | 28 | Input: nums = [5,7,7,8,8,10], target = 6 29 | 30 | Output: [-1,-1] 31 | 32 | ### Example 3: 33 | 34 | Input: nums = [], target = 0 35 | 36 | Output: [-1,-1] 37 | -------------------------------------------------------------------------------- /Cpp/347-Top K frequent Elements/solutioon.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& nums, int k) { 4 | vectorans(k,0); 5 | unordered_mapmp; 6 | for(auto &i:nums){ 7 | mp[i]++; 8 | } 9 | multimap>m; 10 | for(auto &j:mp){ 11 | m.insert({j.second,j.first}); 12 | } 13 | int cnt=0; 14 | for(auto &i:m){ 15 | ans[cnt]=i.second; 16 | cnt++; 17 | if(cnt==k)break; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Cpp/3Sum/problem.md: -------------------------------------------------------------------------------- 1 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 2 | 3 | Notice that the solution set must not contain duplicate triplets. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: nums = [-1,0,1,2,-1,-4] 10 | Output: [[-1,-1,2],[-1,0,1]] 11 | Explanation: 12 | nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. 13 | nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. 14 | nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. 15 | The distinct triplets are [-1,0,1] and [-1,-1,2]. 16 | Notice that the order of the output and the order of the triplets does not matter. 17 | Example 2: 18 | 19 | Input: nums = [0,1,1] 20 | Output: [] 21 | Explanation: The only possible triplet does not sum up to 0. 22 | Example 3: 23 | 24 | Input: nums = [0,0,0] 25 | Output: [[0,0,0]] 26 | Explanation: The only possible triplet sums up to 0. 27 | 28 | 29 | Constraints: 30 | 31 | 3 <= nums.length <= 3000 32 | -105 <= nums[i] <= 105 -------------------------------------------------------------------------------- /Cpp/3Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | int n = nums.size(); 5 | sort(nums.begin(), nums.end()); 6 | 7 | set> st; 8 | for(int i=0; i 0) r--; 17 | else l++; 18 | } 19 | } 20 | 21 | vector> res; 22 | for(auto &v: st){ 23 | res.push_back(v); 24 | } 25 | return res; 26 | } 27 | }; -------------------------------------------------------------------------------- /Cpp/48. Rotate Image/problem.md: -------------------------------------------------------------------------------- 1 | # 48. Rotate Image 2 | 3 | [Problem Link](https://leetcode.com/problems/rotate-image/description/) 4 | 5 | ## Problem Description 6 | You are given an `n x n` 2D matrix representing an image, and you need to rotate the image by 90 degrees clockwise. 7 | 8 | You must rotate the image **in-place**, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix for the rotation. 9 | 10 | ### Constraints 11 | - `n == matrix.length == matrix[i].length` 12 | - `1 <= n <= 20` 13 | - `-1000 <= matrix[i][j] <= 1000` 14 | 15 | ## Examples 16 | 17 | ### Example 1 18 | ![Example 1](https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg) 19 | 20 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 21 | Output: [[7,4,1],[8,5,2],[9,6,3] 22 | 23 | ### Example 2 24 | ![Example 2](https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg) 25 | 26 | Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] 27 | Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] -------------------------------------------------------------------------------- /Cpp/48. Rotate Image/solution.cpp: -------------------------------------------------------------------------------- 1 | // Q. You are given an n x n 2D matrix representing an image, 2 | // rotate the image by 90 degrees (clockwise). 3 | // (You have to rotate the image in-place, which means you have to modify 4 | // the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.) 5 | 6 | 7 | class Solution { 8 | public: 9 | void rotate(vector>& matrix) { 10 | 11 | //First we take the transpose of the matrix, 12 | //In transpose , the i and j are interchanged , or flipped accross , i = j ; 13 | int n = matrix.size(); 14 | for(int i = 0;i& letters, char target) { 4 | 5 | int ind = upper_bound(letters.begin(), letters.end(), target) - letters.begin(); 6 | return (ind != letters.size()) ? letters[ind] : letters[0]; 7 | } 8 | }; -------------------------------------------------------------------------------- /Cpp/76-Minimum Window Substring/problem.md: -------------------------------------------------------------------------------- 1 | ## 76. Minimum Window Substring 2 | 3 | Given two string `s` and `t` of lenght `m` and `n` respectively, return the *minimum window substring* of `s` *such that every character int `t` **(includeing duplicates)*** is *included in the window.* If there is no such substring, return an empty string `""`. 4 | 5 | **Input:** `s = "ADOBECODEBANC", t = "ABC"` 6 | 7 | **Output:** `"BANC"` 8 | 9 | **Explanation:** The minimum window substring "BANC" includes all characters 'A', 'B', and 'C' from string `t`. 10 | 11 | ### Function Signature 12 | 13 | ```cpp 14 | class Solution { 15 | public: 16 | int shortestPathLength(vector>& graph); 17 | }; 18 | -------------------------------------------------------------------------------- /Cpp/80_Remove_duplicates_from_sorted_array_II/solution1.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int k = 2; // Initialize k to 2, allowing at most two duplicates 5 | 6 | // If the array size is less than or equal to 2, return its size (no duplicates to remove) 7 | if (nums.size() <= 2) return nums.size(); 8 | 9 | // Iterate through the array starting from the third element (index 2) 10 | for (int i = 2; i < nums.size(); i++) { 11 | // Check if the current number is different from the number at index k-2 12 | if (nums[i] != nums[k - 2]) { 13 | // If different, assign the current number to the position indexed by k 14 | nums[k] = nums[i]; 15 | k++; // Increment k to point to the next position 16 | } 17 | } 18 | 19 | // Return the new length of the array with allowed duplicates 20 | return k; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Cpp/80_Remove_duplicates_from_sorted_array_II/solution2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int l = 0, r = 0, count = 0; // Initialize pointers and count 5 | 6 | while (r < nums.size()) { 7 | count = 1; // Reset count for each new number 8 | 9 | // Count duplicates 10 | while ((r + 1) < nums.size() && nums[r] == nums[r + 1]) { 11 | r++; 12 | count++; 13 | } 14 | 15 | // Allow at most 2 duplicates in the result 16 | for (int i = 0; i < min(2, count); i++) { 17 | nums[l] = nums[r]; // Store the allowed duplicates 18 | l++; // Move the left pointer 19 | } 20 | r++; // Move to the next unique number 21 | } 22 | 23 | return l; // Return the new length of the array 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Cpp/834-Sum-of-Distance-in-Tree/problem.md: -------------------------------------------------------------------------------- 1 | There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. 2 | 3 | You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. 4 | 5 | Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes. 6 | 7 | Exapmle 1 8 | 9 | Input: 10 | 11 | n = 6, dges = [[0,1],[0,2],[2,3],[2,4],[2,5]] 12 | 13 | Output: [8,12,6,10,10,10] 14 | 15 | Explanation: 16 | 17 | The tree is shown above. 18 | We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) 19 | 20 | equals 1 + 1 + 2 + 2 + 2 = 8. 21 | 22 | Hence, answer[0] = 8, and so on. 23 | 24 | Example 2 25 | 26 | Input: 27 | 28 | n = 1, edges = [] 29 | 30 | Output: [0] 31 | 32 | Example 3 33 | 34 | Input: 35 | 36 | n = 2, edges = [[1,0]] 37 | 38 | Output: [1,1] -------------------------------------------------------------------------------- /Cpp/847. Shortest Path Visiting All Nodes/Screenshot 2024-10-02 at 12.42.30 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/Cpp/847. Shortest Path Visiting All Nodes/Screenshot 2024-10-02 at 12.42.30 PM.png -------------------------------------------------------------------------------- /Cpp/847. Shortest Path Visiting All Nodes/problem.md: -------------------------------------------------------------------------------- 1 | ## 847 Shortest Path Visiting All Nodes 2 | 3 | You are given an undirected, connected graph with `n` nodes labeled from `0` to `n - 1`. You are given an array garph were `graph[i]` is a list of all nodes connected with node `i` by an egde. 4 | 5 | Return *length of the shortest path that visits every node*. You may start and stop at any node, you may revisit nodes multipile time, and you may reuse edges. 6 | 7 | **Example 1:** 8 | 9 | ![alt text]() 10 | 11 | **Input :** graph = `[[1,2,3], [0], [0], [0]]` 12 | 13 | **Output** = `4` 14 | 15 | **Explanation**: One Possible path is `[1, 0, 2, 0, 3]` 16 | ### Function Signature 17 | 18 | ```cpp 19 | class Solution { 20 | public: 21 | int shortestPathLength(vector>& graph); 22 | }; 23 | -------------------------------------------------------------------------------- /Cpp/987. Vertical Order Traversal of a Binary Tree/problem.md: -------------------------------------------------------------------------------- 1 | Given the root of a binary tree, calculate the vertical order traversal of the binary tree. 2 | 3 | For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). 4 | 5 | The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. 6 | 7 | Return the vertical order traversal of the binary tree. -------------------------------------------------------------------------------- /Cpp/99_Recover Binary Search Tree/problem.md: -------------------------------------------------------------------------------- 1 | You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. 2 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 3 | 4 | Example 1: 5 | 6 | Input: root = [1,3,null,null,2] 7 | Output: [3,1,null,null,2] 8 | Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. 9 | 10 | Example 2: 11 | 12 | Input: root = [3,1,4,null,null,2] 13 | Output: [2,1,4,null,null,3] 14 | Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid. 15 | 16 | Constraints: 17 | 18 | The number of nodes in each linked list is in the range [1, 100]. 19 | 0 <= Node.val <= 9 20 | It is guaranteed that the list represents a number that does not have leading zeros. 21 | 22 | Constraints: 23 | 24 | The number of nodes in the tree is in the range [2, 1000]. 25 | -231 <= Node.val <= 231 - 1 26 | 27 | Follow up: A solution using O(n) space is pretty straight-forward. Could you devise a constant O(1) space solution? 28 | -------------------------------------------------------------------------------- /Cpp/Air-Quality-Index/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n; 6 | cin>>n; 7 | if(n<100){ 8 | cout<<"YES"; 9 | } 10 | else{ 11 | cout<<"NO"; 12 | } 13 | return 0; 14 | } -------------------------------------------------------------------------------- /Cpp/Another permutation problem/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define ll long long 3 | #define int long long 4 | using namespace std; 5 | signed main(){ 6 | int t; 7 | cin>>t; 8 | while(t--){ 9 | ll n; 10 | cin>>n; 11 | 12 | vectoractual(n); 13 | for(int i=0;i arr=actual; 19 | reverse(arr.begin()+rev,arr.end()); 20 | ll curr=0,maxi=0; 21 | 22 | for(int i=0;i arr[j] and i < j. 2 | 3 | Inversion Count: For an array, inversion count indicates how far (or close) the array is from being sorted. If the array is already sorted then the inversion count is 0. 4 | If an array is sorted in the reverse order then the inversion count is the maximum. 5 | 6 | 7 | Input: arr[] = [2, 4, 1, 3, 5] 8 | Output: 3 9 | Explanation: The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3). 10 | 11 | 12 | Expected Time Complexity: O(n*logn). 13 | Expected Auxiliary Space: O(n). 14 | 15 | Constraints: 16 | 1 ≤ arr.size(),arr[i] ≤ 105 -------------------------------------------------------------------------------- /Cpp/Dardos/problem.md: -------------------------------------------------------------------------------- 1 | ## Greedy Darts 2 | It is desired to implement a type of darts game, where three types of game modes will be allowed: 3 | 1 = only single values sections can be used, double or triple setions are worth 0 4 | 2 = only double areas score, all other areas are worth 0 5 | 3 = only triple areas score, all other areas are worth 0 6 | The centre of tha board is always 0. 7 | 8 | The aim is to archieve a specific score P, using the least number of darts and the selected game mode {1,2,3} 9 | 10 | #### Example 11 | To archieve P = 63 in game mode 3 12 | We need a 20 and 1 with 2 shoots 13 | 14 | To archieve P = 146 in game mode 2 15 | We need three 20 and 13 with 4 shoots 16 | 17 | #### Function Description 18 | 19 | The function has the following parameter(s): 20 | main: 21 | - `int argc`: file that contains the game mode, the score P and the board 22 | 23 | numDardosGreedy 24 | - `set zonas`: the game board 25 | - `int modo`: game mode 26 | - `int puntuacion`: score P 27 | 28 | #### Returns 29 | 30 | - returns if is possible find a Greedy solution, if is not, returns error. 31 | 32 | 33 | -------------------------------------------------------------------------------- /Cpp/Diameter of a tree/problem.md: -------------------------------------------------------------------------------- 1 | ### Problem Statement 2 | 3 | **Given the root of a binary tree, return the length of the diameter of the tree.** 4 | 5 | The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 6 | 7 | The length of a path between two nodes is represented by the number of edges between them. 8 | 9 | #### Example 1: 10 | 11 | **Input:** 12 | root = [1,2,3,4,5] 13 | **Output:** 14 | 3 15 | **Explanation:** 16 | 3 is the length of the path [4,2,1,3] or [5,2,1,3]. 17 | 18 | #### Example 2: 19 | 20 | **Input:** 21 | root = [1,2] 22 | **Output:** 23 | 1 24 | 25 | 26 | #### Constraints: 27 | - The number of nodes in the tree is in the range [1, 10^4]. 28 | - -100 <= Node.val <= 100 -------------------------------------------------------------------------------- /Cpp/Dota2-senate/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | string predictPartyVictory(string senate) { 6 | int n = senate.size(); 7 | queue radiant, dire; 8 | 9 | for (int i = 0; i < n; i++) { 10 | if (senate[i] == 'R') radiant.push(i); 11 | else dire.push(i); 12 | } 13 | 14 | while (!radiant.empty() && !dire.empty()) { 15 | int r_index = radiant.front(); 16 | int d_index = dire.front(); 17 | 18 | if (r_index < d_index) { 19 | radiant.push(r_index + n); 20 | } else { 21 | dire.push(d_index + n); 22 | } 23 | 24 | radiant.pop(); 25 | dire.pop(); 26 | } 27 | 28 | return radiant.empty() ? "Dire" : "Radiant"; 29 | } 30 | 31 | int main() { 32 | string senate = "RDD"; 33 | string result = predictPartyVictory(senate); 34 | cout << "The party that will announce victory: " << result << endl; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Cpp/Josephus_prob/problem.md: -------------------------------------------------------------------------------- 1 | # Josephus Problem 2 | 3 | The **Josephus Problem** is a theoretical problem related to a certain elimination game. It can be described as follows: 4 | 5 | ## Problem Description 6 | 7 | **N people are standing in a circle.** Starting with the first person, a count is made up to K. The K-th person is eliminated from the circle, and the process is repeated with the next person in the circle. This continues until only one person remains, who is considered to be in the "safe position." 8 | 9 | The objective is to find the safe position. 10 | 11 | ### Example 12 | For `n = 5` (5 people) and `k = 2` (every second person is eliminated): 13 | - The order of elimination will be: 2, 4, 1, 5. 14 | - The last remaining person (safe position) is 3. 15 | 16 | -------------------------------------------------------------------------------- /Cpp/Josephus_prob/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to calculate the safe position in the Josephus problem 5 | int josephus(int n, int k) { 6 | // Base case: if there is only one person left, that person is safe 7 | if (n == 1) 8 | return 0; // Index starts from 0, so return 0 as the safe position 9 | // Recursive case: reduce the problem size by one person, and adjust the position 10 | return (josephus(n - 1, k) + k) % n; 11 | } 12 | 13 | int main() { 14 | int n, k; 15 | 16 | // Take input for number of people (n) and step count (k) 17 | cout << "Enter the number of people: "; 18 | cin >> n; 19 | cout << "Enter the step count: "; 20 | cin >> k; 21 | 22 | // Calculate the safe position, convert from 0-indexed to 1-indexed by adding 1 23 | int result = josephus(n, k) + 1; 24 | 25 | // Output the safe position 26 | cout << "The safe position is: " << result << endl; 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Cpp/Longest Common Subsequence/problem.md: -------------------------------------------------------------------------------- 1 | Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. 2 | 3 | A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. 4 | 5 | For example, "ace" is a subsequence of "abcde". 6 | A common subsequence of two strings is a subsequence that is common to both strings. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: text1 = "abcde", text2 = "ace" 13 | Output: 3 14 | Explanation: The longest common subsequence is "ace" and its length is 3. 15 | Example 2: 16 | 17 | Input: text1 = "abc", text2 = "abc" 18 | Output: 3 19 | Explanation: The longest common subsequence is "abc" and its length is 3. 20 | Example 3: 21 | 22 | Input: text1 = "abc", text2 = "def" 23 | Output: 0 24 | Explanation: There is no such common subsequence, so the result is 0. 25 | 26 | 27 | Constraints: 28 | 29 | 1 <= text1.length, text2.length <= 1000 30 | text1 and text2 consist of only lowercase English characters. -------------------------------------------------------------------------------- /Cpp/Longest Unequal Adjacent Groups Subsequence I/problem.md: -------------------------------------------------------------------------------- 1 | Longest Unequal Adjacent Groups Subsequence I 2 | 3 | You are given an integer n, a 0-indexed string array words, and a 0-indexed binary array groups, both arrays having length n. 4 | 5 | You need to select the longest subsequence from an array of indices [0, 1, ..., n - 1], such that for the subsequence denoted as [i0, i1, ..., ik - 1] having length k, groups[ij] != groups[ij + 1], for each j where 0 < j + 1 < k. 6 | 7 | Return a string array containing the words corresponding to the indices (in order) in the selected subsequence. If there are multiple answers, return any of them. 8 | 9 | A subsequence of an array is a new array that is formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements. 10 | 11 | Note: strings in words may be unequal in length. 12 | 13 | 14 | Constraints: 15 | 16 | 1 <= n == words.length == groups.length <= 100 17 | 1 <= words[i].length <= 10 18 | 0 <= groups[i] < 2 19 | words consists of distinct strings. 20 | words[i] consists of lowercase English letters. -------------------------------------------------------------------------------- /Cpp/Longest repeating character replacement/problem.md: -------------------------------------------------------------------------------- 1 | You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. 2 | 3 | Return the length of the longest substring containing the same letter you can get after performing the above operations. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: s = "ABAB", k = 2 10 | Output: 4 11 | Explanation: Replace the two 'A's with two 'B's or vice versa. -------------------------------------------------------------------------------- /Cpp/Magical calendar/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define ll long long 3 | #define int long long 4 | using namespace std; 5 | signed main(){ 6 | int t; 7 | cin>>t; 8 | while(t--){ 9 | ll n,r; 10 | cin >> n >> r; 11 | ll ans=0; 12 | if(r>=n) 13 | ans=n*(n-1)/2+1; 14 | else 15 | ans=r*(r+1)/2; 16 | cout< 2 | using namespace std; 3 | int main() { 4 | 5 | int T; cin >> T; 6 | while(T--) { 7 | int N, X; cin >> N >> X; 8 | int F = N+1, L = -1; 9 | int S = 0; 10 | for(int i=0;i> cur; 12 | S += cur; S %= X; 13 | if (cur % X != 0) { 14 | F = min(F, i); L = max(L, i); 15 | } 16 | } 17 | if (S % X != 0) { 18 | cout << N << "\n"; 19 | } else if (L == -1) { 20 | cout << -1 << "\n"; 21 | } else { 22 | cout << max(N-F-1, L) << "\n"; 23 | } 24 | } 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Cpp/Number of Enclaves/problem.md: -------------------------------------------------------------------------------- 1 | You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. 2 | 3 | A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. 4 | 5 | Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves. 6 | 7 | Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] 8 | Output: 3 9 | Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. 10 | 11 | Constraints: 12 | 13 | m == grid.length 14 | n == grid[i].length 15 | 1 <= m, n <= 500 16 | grid[i][j] is either 0 or 1. -------------------------------------------------------------------------------- /Cpp/Painter's Partition Problem/Problem.md: -------------------------------------------------------------------------------- 1 | Problem statement 2 | 3 | Given an array/list of length ‘n’, where the array/list represents the boards and each element of the given array/list represents the length of each board. Some ‘k’ numbers of painters are available to paint these boards. Consider that each unit of a board takes 1 unit of time to paint. 4 | 5 | 6 | 7 | You are supposed to return the area of the minimum time to get this job done of painting all the ‘n’ boards under a constraint that any painter will only paint the continuous sections of boards. 8 | 9 | 10 | 11 | Example : 12 | Input: arr = [2, 1, 5, 6, 2, 3], k = 2 13 | 14 | Output: 11 15 | 16 | Explanation: 17 | First painter can paint boards 1 to 3 in 8 units of time and the second painter can paint boards 4-6 in 11 units of time. Thus both painters will paint all the boards in max(8,11) = 11 units of time. It can be shown that all the boards can't be painted in less than 11 units of time. -------------------------------------------------------------------------------- /Cpp/Pairs with Given Sum/problem.md: -------------------------------------------------------------------------------- 1 | Problem Description: 2 | 3 | You are given an array of integers nums and an integer k. Your task is to find the number of unique pairs of integers in the array that sum up to the given value k. 4 | 5 | Write a function findPairs(nums, k) that returns the count of unique pairs that satisfy this condition. 6 | 7 | Input: 8 | 9 | An array nums of integers (1 <= |nums| <= 10^5), where |nums| represents the number of elements in the array. 10 | An integer k (-10^7 <= k <= 10^7). 11 | Output: 12 | 13 | An integer representing the count of unique pairs that sum up to k. 14 | Constraints: 15 | 16 | Each element in nums is unique. 17 | The order of the elements in the output does not matter. 18 | A pair (a, b) is considered unique, and a pair (b, a) is not counted as a separate pair. 19 | The input values are within the valid range. 20 | Example: 21 | 22 | Input: 23 | nums = [1, 2, 3, 4, 5] 24 | k = 5 25 | 26 | Output: 27 | 2 28 | 29 | Explanation: 30 | 31 | In the given array [1, 2, 3, 4, 5], there are two unique pairs that sum up to 5: (1, 4) and (2, 3). Therefore, the output is 2. -------------------------------------------------------------------------------- /Cpp/Rotate-an-array-by-K/problem.md: -------------------------------------------------------------------------------- 1 | ##Rotate an array by K 2 | 3 | Given an array with n element, the task is to rotate the array to the left by 'k' steps, where 'k' is non-negative 4 | 5 | Example: 6 | 7 | ' arr '=[1,2,3,4,5] 8 | 'k' = 1 [2,3,4,5,1] 9 | 'k' = 2 [3,4,5,1,2] 10 | 'k' = 3 [4,5,1,2,3] and so on... 11 | -------------------------------------------------------------------------------- /Cpp/Rotate-an-array-by-K/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void Rotatetoright(int arr[], int n, int k) 4 | { 5 | if (n == 0) 6 | return; 7 | k = k % n; 8 | if (k > n) 9 | return; 10 | int temp[k]; 11 | for (int i = n - k; i < n; i++) 12 | { 13 | temp[i - n + k] = arr[i]; 14 | } 15 | for (int i = n - k - 1; i >= 0; i--) 16 | { 17 | arr[i + k] = arr[i]; 18 | } 19 | for (int i = 0; i < k; i++) 20 | { 21 | arr[i] = temp[i]; 22 | } 23 | } 24 | int main() 25 | { 26 | int n = 7; 27 | int arr[] = {1, 2, 3, 4, 5, 6, 7}; 28 | int k = 2; 29 | Rotatetoright(arr, n, k); 30 | cout << "After Rotating the elements to right " << endl; 31 | for (int i = 0; i < n; i++) 32 | { 33 | cout << arr[i] << " "; 34 | } 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Cpp/Rotate-an-array-by-K/solution2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // Function to Reverse the array 4 | void Reverse(int arr[], int start, int end) 5 | { 6 | while (start <= end) 7 | { 8 | int temp = arr[start]; 9 | arr[start] = arr[end]; 10 | arr[end] = temp; 11 | start++; 12 | end--; 13 | } 14 | } 15 | // Function to Rotate k elements to left 16 | void Rotateeletoleft(int arr[], int n, int k) 17 | { 18 | // Reverse first k elements 19 | Reverse(arr, 0, k - 1); 20 | // Reverse last n-k elements 21 | Reverse(arr, k, n - 1); 22 | // Reverse whole array 23 | Reverse(arr, 0, n - 1); 24 | } 25 | int main() 26 | { 27 | int arr[] = {1, 2, 3, 4, 5, 6, 7}; 28 | int n = 7; 29 | int k = 2; 30 | Rotateeletoleft(arr, n, k); 31 | cout << "After Rotating the k elements to left "; 32 | for (int i = 0; i < n; i++) 33 | cout << arr[i] << " "; 34 | cout << endl; 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Cpp/Top K Frequent Elements/problem.md: -------------------------------------------------------------------------------- 1 | Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. 2 | 3 | Example 1: 4 | Input: nums = [1,1,1,2,2,3], k = 2 5 | Output: [1,2] 6 | 7 | Example 2: 8 | Input: nums = [1], k = 1 9 | Output: [1] 10 | 11 | Constraints: 12 | 1 <= nums.length <= 10^5 13 | -10^4 <= nums[i] <= 10^4 14 | k is in the range [1, the number of unique elements in the array]. 15 | It is guaranteed that the answer is unique. 16 | -------------------------------------------------------------------------------- /Cpp/Top K Frequent Elements/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& nums, int z) { 4 | vectora(z); 5 | map m; 6 | int y, maxf, b; 7 | for(int i = 0; i::iterator mn, it; 13 | it = m.begin(); 14 | while(it!=m.end()){ 15 | y = it->second; 16 | if(y>maxf){ 17 | maxf = y; 18 | b = it->first; 19 | mn = it; 20 | } 21 | it++; 22 | } 23 | a[i] = b; 24 | mn->second = 0; 25 | } 26 | return a; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Cpp/Two-Sum/problem.md: -------------------------------------------------------------------------------- 1 | Problem Description: 2 | 3 | You are given an array of integers nums and an integer target. Your task is to find two numbers in the array that add up to the given target. 4 | 5 | Write a function twoSum(nums, target) that returns the indices of the two numbers in the array that add up to the target. 6 | 7 | Input: 8 | 9 | An array nums of integers (2 <= |nums| <= 10^5), where |nums| represents the number of elements in the array. 10 | An integer target (-10^9 <= target <= 10^9). 11 | Output: 12 | 13 | A vector of two integers representing the indices of the two numbers in the array that add up to the target. 14 | Constraints: 15 | 16 | Each input has exactly one solution, and you may not use the same element twice. 17 | The order of the elements in the output does not matter. 18 | Example: 19 | 20 | Input: 21 | nums = [2, 7, 11, 15] 22 | target = 9 23 | 24 | Output: 25 | [0, 1] 26 | 27 | Explanation: 28 | 29 | In the given array [2, 7, 11, 15], the numbers at indices 0 and 1 (2 and 7) add up to the target 9. Therefore, the output is [0, 1]. -------------------------------------------------------------------------------- /Cpp/Unique Path/problem.md: -------------------------------------------------------------------------------- 1 | Problem - Unique Grid Path 2 | 3 | There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. 4 | 5 | Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. 6 | 7 | The test cases are generated so that the answer will be less than or equal to 2 * 109. 8 | 9 | 10 | 11 | Input: m = 3, n = 2 12 | Output: 3 13 | Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 14 | 1. Right -> Down -> Down 15 | 2. Down -> Down -> Right 16 | 3. Down -> Right -> Down 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= m, n <= 100 -------------------------------------------------------------------------------- /Cpp/Witua-and-maths/problem.md: -------------------------------------------------------------------------------- 1 | Witua is a little student from the University of Lviv. He enjoys studying math. Witua knows a lot of famous mathematicians like Eratosthenes, Pythagoras, Fermat, Diophantus, Furko, Gauss and so on. However, his favorite one is Euler. The only thing Witua likes more than Euler is Euler’s totient function φ. He is exploring the nature of this function. One of the steps of his work is finding φ(i)/i for all 2≤i≤N. He doesn’t need to know every such value, but Witua wonders for what value i, is φ(i)/i the maximum he can get? Help little student to find such i that φ(i)/i is maximum among all the 2≤i≤N. 2 | 3 | Input 4 | The first line contains single integer T - the number of test cases. Each of the next T lines contains a single integer N. 5 | 6 | Output 7 | For every test case output i such that φ(i)/i is maximum among all i (2≤i≤N) in a separate line. 8 | 9 | Constrains 10 | T (1≤T≤500 ) 11 | 12 | N(2≤N≤10^18) 13 | 14 | Sample 1: 15 | Input 16 | 3 17 | 2 18 | 3 19 | 4 20 | Output 21 | 2 22 | 3 23 | 3 24 | Explanation: 25 | ?(2)/2=1/2 ?(3)/3=2/3 ?(4)/4=2/4 -------------------------------------------------------------------------------- /Cpp/add-binary/problem.md: -------------------------------------------------------------------------------- 1 | ## Add Binary 2 | 3 | Given two binary strings `a` and `b`, return their sum as a binary string. 4 | 5 | #### Constraints: 6 | 7 | - `1 <= a.length, b.length <= 104` 8 | - `a` and `b` consist only of `'0'` or `'1'` characters. 9 | - Each string does not contain leading zeros except for the zero itself. 10 | -------------------------------------------------------------------------------- /Cpp/add-binary/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | string addBinary(string a, string b) 5 | { 6 | string result; 7 | int carry = 0; 8 | int i = a.length() - 1; 9 | int j = b.length() - 1; 10 | 11 | while (i >= 0 || j >= 0 || carry > 0) 12 | { 13 | int sum = carry; 14 | 15 | if (i >= 0) 16 | { 17 | sum += a[i] - '0'; 18 | i--; 19 | } 20 | 21 | if (j >= 0) 22 | { 23 | sum += b[j] - '0'; 24 | j--; 25 | } 26 | 27 | result = char((sum % 2) + '0') + result; 28 | carry = sum / 2; 29 | } 30 | 31 | return result; 32 | } 33 | 34 | int main() 35 | { 36 | string a = "1010"; 37 | string b = "1011"; 38 | 39 | string str = addBinary(a, b); 40 | cout << str << endl; 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Cpp/angry-professor/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | string angryProfessor(int k, vector arr) 6 | { 7 | int noOfStudents = 0; 8 | 9 | for (int arrivalTime : arr) 10 | { 11 | if (arrivalTime <= 0) 12 | noOfStudents++; 13 | } 14 | 15 | if (noOfStudents >= k) 16 | return "class not cancelled"; 17 | else 18 | return "class cancelled"; 19 | } 20 | 21 | int main() 22 | { 23 | int t; 24 | cout << "Size: "; 25 | cin >> t; 26 | 27 | for (int i = 0; i < t; i++) 28 | { 29 | int n, k; 30 | cout << "Enter Size of an array: "; 31 | cin >> n; 32 | 33 | cout << "Enter threshold number of students: "; 34 | cin >> k; 35 | 36 | vector arr(n); 37 | for (int j = 0; j < n; j++) 38 | { 39 | cout << "Enter arrival time of the students: "; 40 | cin >> arr[j]; 41 | } 42 | string result = angryProfessor(k, arr); 43 | cout << "Result: " << result << endl; 44 | } 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /Cpp/beautiful-days-at-the-movies/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int reverseDays(int day) 5 | { 6 | int reversedNumber = 0; 7 | while (day > 0) 8 | { 9 | reversedNumber = reversedNumber * 10 + day % 10; 10 | day /= 10; 11 | } 12 | return reversedNumber; 13 | } 14 | 15 | int beautifulDays(int i, int j, int k) 16 | { 17 | int beautifulDaysCount = 0; 18 | 19 | for (int days = i; days <= j; days++) 20 | { 21 | int reverse = reverseDays(days); 22 | int difference = abs(days - reverse); 23 | 24 | if (difference % k == 0) 25 | beautifulDaysCount++; 26 | } 27 | 28 | return beautifulDaysCount; 29 | } 30 | 31 | int main() 32 | { 33 | int i, j, k; 34 | cout << "Enter the starting day: "; 35 | cin >> i; 36 | 37 | cout << "Enter the ending day: "; 38 | cin >> j; 39 | 40 | cout << "Enter the divisor: "; 41 | cin >> k; 42 | 43 | int result = beautifulDays(i, j, k); 44 | cout << "Result: " << result << endl; 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Cpp/binary-tree-maximum-path-sum/problem.md: -------------------------------------------------------------------------------- 1 | # Binary tree maximum path sum 2 | 3 | ## Problem Description 4 | 5 | A path in a binary tree is defined as a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can appear in the sequence only once. Importantly, the path does not need to pass through the root. 6 | 7 | The **path sum** of a path is the sum of the node values along that path. 8 | 9 | Given the `root` of a binary tree, return the **maximum path sum** of any non-empty path. 10 | 11 | --- 12 | 13 | ## Examples 14 | 15 | **Input 1:** 16 | 17 | ```plaintext 18 | root = [1,2,3] 19 | ``` 20 | 21 | **Output 1:** 22 | 23 | ```plaintext 24 | 6 25 | ``` 26 | 27 | **Input 2:** 28 | 29 | ```plaintext 30 | root = [-10,9,20,null,null,15,7] 31 | ``` 32 | 33 | **Output 2:** 34 | 35 | ```plaintext 36 | 42 37 | ``` 38 | 39 | --- 40 | 41 | ## Constraints 42 | 43 | - The number of nodes in the tree is in the range `[1, 3 * 10^4]`. 44 | - Each node's value is in the range `[-1000, 1000]`. 45 | -------------------------------------------------------------------------------- /Cpp/birthday-bar/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int birthday(int arr[], int n, int d, int m) 5 | { 6 | int ways = 0; 7 | 8 | for (int i = 0; i <= n - m; i++) 9 | { 10 | int sum = 0; 11 | for (int j = i; j < i + m; j++) 12 | sum += arr[j]; 13 | 14 | // Check if the sum equals the birth-day. Increment number of ways. 15 | if (sum == d) 16 | ways++; 17 | } 18 | 19 | return ways; 20 | } 21 | 22 | int main() 23 | { 24 | int size, d, m; 25 | 26 | cout << "Enter size of an array: "; 27 | cin >> size; 28 | 29 | int arr[size]; 30 | for (int i = 0; i < size; i++) 31 | { 32 | cout << "Enter element: "; 33 | cin >> arr[i]; 34 | } 35 | 36 | cout << "Enter birthday: "; 37 | cin >> d; 38 | 39 | cout << "Enter birth-month: "; 40 | cin >> m; 41 | 42 | int result = birthday(arr, size, d, m); 43 | cout << "Result: " << result << endl; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Cpp/birthday-cake-candles/problem.md: -------------------------------------------------------------------------------- 1 | ## Birthday Cake Candles 2 | 3 | You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest. 4 | 5 | #### Example 6 | 7 | - _candles = [4, 4, 1, 3]_ 8 | 9 | - The maximum height candles are _4_ units high. There are _2_ of them, so return _2_. 10 | 11 | #### Function Description 12 | 13 | The function has the following parameter(s): 14 | 15 | - **int candles[n]**: the candle heights 16 | 17 | #### Returns 18 | 19 | - **int**: the number of candles that are tallest 20 | 21 | #### Input Format 22 | 23 | - The first line contains a single integer, _n_, the size of _candles[]_. 24 | - The second line contains _n_ space-separated integers, where each integer _i_ describes the height of _candles[i]_. 25 | 26 | #### Constraints 27 | 28 | - 1 <= n <= 10^5 29 | - 1 <= candles[i] <= 10^7 30 | -------------------------------------------------------------------------------- /Cpp/breaking-the-records/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | vector breakingRecords(vector scores) 6 | { 7 | int minScore = scores[0]; 8 | int maxScore = scores[0]; 9 | int minCount = 0; 10 | int maxCount = 0; 11 | 12 | for (int i = 1; i < scores.size(); i++) 13 | { 14 | if (scores[i] < minScore) 15 | { 16 | minScore = scores[i]; 17 | minCount++; 18 | } 19 | else if (scores[i] > maxScore) 20 | { 21 | maxScore = scores[i]; 22 | maxCount++; 23 | } 24 | } 25 | 26 | return {maxCount, minCount}; 27 | } 28 | 29 | int main() 30 | { 31 | int n; 32 | cout << "Enter Size: "; 33 | cin >> n; 34 | 35 | vector scores(n); 36 | for (int i = 0; i < n; i++) 37 | { 38 | cout << "Enter elements: "; 39 | cin >> scores[i]; 40 | } 41 | 42 | vector counts = breakingRecords(scores); 43 | 44 | for (int count : counts) 45 | cout << count << " "; 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /Cpp/buy-sell-stock/problem.md: -------------------------------------------------------------------------------- 1 | ## Buy and Sell Stock 2 | 3 | You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. 4 | 5 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 6 | 7 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 8 | 9 | #### Constraints: 10 | 11 | - `1 <= prices.length <= 105` 12 | - `0 <= prices[i] <= 104` 13 | -------------------------------------------------------------------------------- /Cpp/buy-sell-stock/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int maxProfit(int price[], int start, int end) 5 | { 6 | 7 | if (end <= start) 8 | { 9 | return 0; 10 | } 11 | int profit = 0; 12 | int i, j; 13 | for (i = start; i < end; i++) 14 | { 15 | for (j = i + 1; j <= end; j++) 16 | { 17 | if (price[j] > price[i]) 18 | { 19 | int current_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); 20 | 21 | profit = max(profit, current_profit); 22 | } 23 | } 24 | } 25 | return profit; 26 | } 27 | 28 | int main() 29 | { 30 | int price[] = {110, 130, 220, 500, 140, 35, 65}; 31 | int size = sizeof(price) / sizeof(price[0]); 32 | cout << "Profit: " << maxProfit(price, 0, size - 1); 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Cpp/can-place-flowers/problem.md: -------------------------------------------------------------------------------- 1 | # Can Place Flowers 2 | 3 | You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in **adjacent** plots. 4 | 5 | Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means empty and `1` means not empty, and an integer `n`, return `true` if `n` new flowers can be planted in the `flowerbed` without violating the no-adjacent-flowers rule and `false` otherwise. 6 | 7 | #### Example 1: 8 | 9 | - Input: flowerbed = [1,0,0,0,1], n = 1 10 | - Output: true 11 | 12 | #### Example 2: 13 | 14 | - Input: flowerbed = [1,0,0,0,1], n = 2 15 | - Output: false 16 | 17 | #### Constraints: 18 | 19 | - `1 <= flowerbed.length <= 2 x 10^4` 20 | - `flowerbed[i]` is `0` or `1`. 21 | - There are no two adjacent flowers in `flowerbed`. 22 | - `0 <= n <= flowerbed.length` 23 | -------------------------------------------------------------------------------- /Cpp/climbing-stairs/problem.md: -------------------------------------------------------------------------------- 1 | ## Climbing Stairs 2 | 3 | You are climbing a staircase. It takes **n** steps to reach the top. 4 | 5 | Each time you can either climb **1** or **2** steps. In how many distinct ways can you climb to the top? 6 | 7 | #### Example 1: 8 | 9 | ``` 10 | Input: n = 2 11 | Output: 2 12 | Explanation: There are two ways to climb to the top. 13 | 1. 1 step + 1 step 14 | 2. 2 steps 15 | ``` 16 | 17 | #### Example 2: 18 | 19 | ``` 20 | Input: n = 3 21 | Output: 3 22 | Explanation: There are three ways to climb to the top. 23 | 1. 1 step + 1 step + 1 step 24 | 2. 1 step + 2 steps 25 | 3. 2 steps + 1 step 26 | ``` 27 | 28 | #### Constraints: 29 | 30 | - `1 <= n <= 45` 31 | -------------------------------------------------------------------------------- /Cpp/climbing-stairs/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int climbStairs(int n) 6 | { 7 | if (n == 0) 8 | return 0; 9 | if (n == 1) 10 | return 1; 11 | 12 | vector dp(n + 1); 13 | dp[0] = 1; 14 | dp[1] = 1; 15 | 16 | for (int i = 2; i <= n; i++) 17 | dp[i] = dp[i - 1] + dp[i - 2]; 18 | 19 | return dp[n]; 20 | } 21 | 22 | int main() 23 | { 24 | int n; 25 | cout << "Enter number of stairs: "; 26 | cin >> n; 27 | 28 | int ways = climbStairs(n); 29 | cout << "Number of ways to climb " << n << " stairs: " << ways << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Cpp/common-divisor/problem.md: -------------------------------------------------------------------------------- 1 | For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). 2 | 3 | Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2. 4 | -------------------------------------------------------------------------------- /Cpp/common-divisor/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void gcdOfStrings(string s1, string s2) 6 | { 7 | int n = s1.size(); 8 | int m = s2.size(); 9 | 10 | if (s1 + s2 != s2 + s1) 11 | return; 12 | 13 | cout << "String is: " << s1.substr(0, std::__gcd(n, m)); 14 | } 15 | 16 | int main() 17 | { 18 | string str1 = "ABCABC"; 19 | string str2 = "ABC"; 20 | gcdOfStrings(str1, str2); 21 | return 0; 22 | } -------------------------------------------------------------------------------- /Cpp/compare-triplets/problem.md: -------------------------------------------------------------------------------- 1 | ## Compare Triplets 2 | 3 | Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty. 4 | 5 | The rating for Alice's challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob's challenge is the triplet b = (b[0], b[1], b[2]). 6 | 7 | The task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1], and a[2] with b[2]. 8 | 9 | If a[i] > b[i], then Alice is awarded 1 point. 10 | If a[i] < b[i], then Bob is awarded 1 point. 11 | If a[i] = b[i], then neither person receives a point. 12 | Comparison points is the total points a person earned. 13 | 14 | Given a and b, determine their respective comparison points. 15 | 16 | compareTriplets has the following parameter(s): 17 | 18 | int a[3]: Alice's challenge rating 19 | int b[3]: Bob's challenge rating 20 | -------------------------------------------------------------------------------- /Cpp/container-with-most-water/problem.md: -------------------------------------------------------------------------------- 1 | ## Container with most water 2 | 3 | You are given an integer array **height** of length _n_. There are _n vertical lines_ drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`. 4 | 5 | Find two lines that together with the x-axis form a container, such that the container contains the most water. 6 | 7 | Return the maximum amount of water a container can store. 8 | 9 | **Notice** that you may not slant the container. 10 | 11 | sudoku-board 12 | -------------------------------------------------------------------------------- /Cpp/container-with-most-water/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int maxArea(vector &height, int n) 6 | { 7 | int left = 0; 8 | int right = n - 1; 9 | int maxWater = 0; 10 | 11 | while (left < right) 12 | { 13 | int currHeight = min(height[left], height[right]); 14 | int currWidth = right - left; 15 | int currArea = currHeight * currWidth; 16 | maxWater = max(maxWater, currArea); 17 | 18 | if (height[left] < height[right]) 19 | { 20 | left++; 21 | } 22 | else 23 | { 24 | right--; 25 | } 26 | } 27 | return maxWater; 28 | } 29 | 30 | int main() 31 | { 32 | int n; 33 | cout << "Enter size: "; 34 | cin >> n; 35 | 36 | vector height(n); 37 | 38 | for (int i = 0; i < n; i++) 39 | { 40 | cout << "Enter elements: "; 41 | cin >> height[i]; 42 | } 43 | 44 | int result = maxArea(height, n); 45 | cout << "Result: " << result << endl; 46 | return 0; 47 | } -------------------------------------------------------------------------------- /Cpp/convert-sorted-array-to-binary-search-tree/problem.md: -------------------------------------------------------------------------------- 1 | ## convert sorted array to binary search tree 2 | 3 | Given an integer array `nums` where the elements are sorted in **ascending order**, convert it to a height-balanced binary search tree. 4 | 5 | #### Constraints: 6 | 7 | - `1 <= nums.length <= 10^4` 8 | - `-10^4 <= nums[i] <= 10^4` 9 | - `nums` is sorted in a **strictly increasing** order. 10 | -------------------------------------------------------------------------------- /Cpp/counting-valleys/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int countingValleys(int steps, string path) 5 | { 6 | int level = 0; // Current altitude level 7 | int valleys = 0; // Count of Valleys 8 | 9 | for (char step : path) 10 | { 11 | if (step == 'U') 12 | level++; // Going Uphill 13 | else 14 | level--; // Going Downhill 15 | 16 | // Check if the valley is completed 17 | if (level == 0 && step == 'U') 18 | valleys++; 19 | } 20 | 21 | return valleys; 22 | } 23 | 24 | int main() 25 | { 26 | int steps; 27 | string path; 28 | 29 | cout << "Steps: "; 30 | cin >> steps; 31 | 32 | cout << "Path: "; 33 | cin >> path; 34 | 35 | int result = countingValleys(steps, path); 36 | cout << "Result: " << result << endl; 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Cpp/cut-the-sticks/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | vector cutTheSticks(vector arr) 7 | { 8 | // Sort the elements 9 | sort(arr.begin(), arr.end()); 10 | 11 | vector result(1, arr.size()); 12 | for (int i = 1; i < arr.size(); i++) 13 | { 14 | // Check if the element is equal to the next element 15 | if (arr[i - 1] != arr[i]) 16 | result.push_back(arr.size() - i); 17 | } 18 | 19 | return result; 20 | } 21 | 22 | int main() 23 | { 24 | int n; 25 | cout << "Size: "; 26 | cin >> n; 27 | 28 | vector arr(n); 29 | for (int i = 0; i < n; i++) 30 | { 31 | cout << "Enter elements: "; 32 | cin >> arr[i]; 33 | } 34 | 35 | vector result = cutTheSticks(arr); 36 | for (int r : result) 37 | cout << "Result: " << r << endl; 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Cpp/day-of-the-programmer/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | string dayOfProgrammer(int year) 5 | { 6 | if (year == 1918) 7 | return "26.09.1918"; 8 | else if ((year < 1918 && year % 4 == 0) || (year > 1918 && ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)))) 9 | return "12.09." + to_string(year); 10 | else 11 | return "13.09." + to_string(year); 12 | } 13 | 14 | int main() 15 | { 16 | int year; 17 | cout << "Enter year: "; 18 | cin >> year; 19 | 20 | string result = dayOfProgrammer(year); 21 | cout << "Result: " << result << endl; 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Cpp/designer-pdf-viewer/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int designerPdfViewer(vector h, string word) 6 | { 7 | int maxHeight = 0; 8 | 9 | for (char c : word) 10 | { 11 | int height = h[c - 'a']; 12 | maxHeight = max(maxHeight, height); 13 | } 14 | 15 | int highlightedArea = maxHeight * word.length(); 16 | return highlightedArea; 17 | } 18 | 19 | int main() 20 | { 21 | int h[26] = {1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 1, 1, 5, 5, 1, 5, 2, 5, 5, 5, 5, 5, 5}; 22 | 23 | vector heights(h, h + sizeof(h) / sizeof(h[0])); 24 | string word; 25 | cout << "Enter the word: "; 26 | cin >> word; 27 | 28 | int result = designerPdfViewer(heights, word); 29 | cout << "Result: " << result << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Cpp/diagonal-difference/problem.md: -------------------------------------------------------------------------------- 1 | ## Diagonal Difference 2 | 3 | Given a square matrix, calculate the absolute difference between the sums of its diagonals. 4 | 5 | For example, the square matrix **arr** is shown below: 6 | 7 | ``` 8 | 1 2 3 9 | 4 5 6 10 | 9 8 9 11 | ``` 12 | 13 | The left-to-right diagonal = **1 + 5 + 9 = 15**. The right to left diagonal = **3 + 5 + 9 = 17**. Their absolute difference is **|15 - 17| = 2**. 14 | 15 | #### Function description 16 | 17 | The function takes the following parameter: 18 | 19 | - **int arr[n][m]**: an array of integers 20 | 21 | #### Return 22 | 23 | - **int**: the absolute diagonal difference 24 | 25 | #### Input Format 26 | 27 | - The first line contains a single integer, _n_, the number of rows and columns in the square matrix _arr_. 28 | - Each of the next _n_ lines describes a row, _arr[i]_, and consists of _n_ space-separated integers _arr[i][j]_. 29 | 30 | #### Constraints 31 | 32 | - -100 <= arr[i][j] <= 100 33 | 34 | #### Output Format 35 | 36 | - Return the absolute difference between the sums of the matrix's two diagonals as a single integer. 37 | -------------------------------------------------------------------------------- /Cpp/diagonal-difference/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int diagonalDiff(int arr[100][100], int n) 5 | { 6 | int ltr = 0; 7 | int rtl = 0; 8 | 9 | for (int i = 0; i < n; i++) 10 | { 11 | ltr += arr[i][i]; 12 | rtl += arr[i][n - 1 - i]; 13 | } 14 | 15 | return abs(ltr - rtl); 16 | } 17 | 18 | int main() 19 | { 20 | int n; 21 | cout << "Size: "; 22 | cin >> n; // Take the size of the matrix 23 | 24 | int arr[100][100]; 25 | 26 | for (int i = 0; i < n; i++) 27 | { 28 | for (int j = 0; j < n; j++) 29 | { 30 | cout << "Row " << i + 1 << ": "; 31 | cin >> arr[i][j]; 32 | } 33 | } 34 | 35 | int result = diagonalDiff(arr, n); 36 | cout << "Result: " << result << endl; 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /Cpp/divisible-sum-pairs/problem.md: -------------------------------------------------------------------------------- 1 | ## Divisible Sum Pairs 2 | 3 | Given an array of integers and a positive integer `k`, determine the number of `(i, j)` pairs where `i < j` and `ar[i] + ar[j]` is divisible by `k`. 4 | 5 | #### Example 6 | 7 | ``` 8 | ar = [1, 2, 3, 4, 5, 6] 9 | k = 5 10 | ``` 11 | 12 | Three pairs meet the criteria: `[1, 4], [2, 3]` and `[4, 6]`. 13 | 14 | #### Function Description 15 | 16 | The function has the following parameter(s): 17 | 18 | - `int n`: the length of array 19 | - `int ar[n]`: an array of integers 20 | - `int k`: the integer divisor 21 | 22 | #### Returns 23 | 24 | - `int`: the number of pairs 25 | 26 | #### Input Format 27 | 28 | - The first line contains `2` space-separated integers, `n` and `k`; 29 | - The second line contains `n` space-separated integers, each a value of `arr[i]`. 30 | 31 | #### Constraints 32 | 33 | - `2 <= n <= 100` 34 | - `1 <= k <= 100` 35 | - `1 <= ar[i] <= 100` 36 | -------------------------------------------------------------------------------- /Cpp/divisible-sum-pairs/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int divisibleSumPairs(int arr[], int n, int k) 5 | { 6 | int count = 0; 7 | for (int i = 0; i < n - 1; i++) 8 | { 9 | for (int j = i + 1; j < n; j++) 10 | { 11 | int sum = arr[i] + arr[j]; 12 | if ((sum % k) == 0) 13 | count++; 14 | } 15 | } 16 | return count; 17 | } 18 | 19 | int main() 20 | { 21 | int size, k; 22 | 23 | cout << "Enter size of an array: "; 24 | cin >> size; 25 | 26 | cout << "Enter k: "; 27 | cin >> k; 28 | 29 | int arr[size]; 30 | for (int i = 0; i < size; i++) 31 | { 32 | cout << "Enter element: "; 33 | cin >> arr[i]; 34 | } 35 | 36 | int result = divisibleSumPairs(arr, size, k); 37 | cout << "Result: " << result << endl; 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Cpp/drawing-book/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int pageCount(int n, int p) 5 | { 6 | int fromFront = p / 2; 7 | int fromBack = (n / 2) - fromFront; 8 | return min(fromBack, fromFront); 9 | } 10 | 11 | int main() 12 | { 13 | int n, p; 14 | cout << "Enter number of pages in the book: "; 15 | cin >> n; 16 | 17 | cout << "Enter page number to turn to: "; 18 | cin >> p; 19 | 20 | int result = pageCount(n, p); 21 | cout << "Minimum number of pages to turn: " << result << endl; 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /Cpp/dungeon-game/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calculateMinimumHP(vector>& dungeon) { 4 | int n = dungeon.size(), m = dungeon[0].size(); 5 | vector> dp(n, vector(m, 0)); 6 | 7 | for(int i=n-1; i>=0; i--){ 8 | for(int j=m-1; j>=0; j--){ 9 | if(i+1>n-1 && j+1>m-1) dp[i][j] = (dungeon[i][j] > 0) ? 1 : abs(dungeon[i][j])+1; 10 | else if(i+1>n-1) dp[i][j] = max(dp[i][j+1] - dungeon[i][j], 1); 11 | else if(j+1>m-1) dp[i][j] = max(dp[i+1][j] - dungeon[i][j], 1); 12 | else{ 13 | int rem = min(dp[i+1][j], dp[i][j+1]); 14 | dp[i][j] = max(rem - dungeon[i][j], 1); 15 | } 16 | } 17 | } 18 | return dp[0][0]; 19 | } 20 | }; -------------------------------------------------------------------------------- /Cpp/edit-distance/problem.md: -------------------------------------------------------------------------------- 1 | Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. 2 | 3 | You have the following three operations permitted on a word: 4 | 5 | Insert a character 6 | Delete a character 7 | Replace a character 8 | 9 | 10 | Example 1: 11 | 12 | Input: word1 = "horse", word2 = "ros" 13 | Output: 3 14 | Explanation: 15 | horse -> rorse (replace 'h' with 'r') 16 | rorse -> rose (remove 'r') 17 | rose -> ros (remove 'e') 18 | Example 2: 19 | 20 | Input: word1 = "intention", word2 = "execution" 21 | Output: 5 22 | Explanation: 23 | intention -> inention (remove 't') 24 | inention -> enention (replace 'i' with 'e') 25 | enention -> exention (replace 'n' with 'x') 26 | exention -> exection (replace 'n' with 'c') 27 | exection -> execution (insert 'u') 28 | 29 | 30 | Constraints: 31 | 32 | 0 <= word1.length, word2.length <= 500 33 | word1 and word2 consist of lowercase English letters. -------------------------------------------------------------------------------- /Cpp/edit-distance/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(string word1, string word2) { 4 | const int inf = INT_MAX; 5 | vector> dp(507, vector (507, inf)); 6 | 7 | int n = word1.size(), m = word2.size(); 8 | for(int i=0; i<=n; i++){ 9 | for(int j=0; j<=m; j++){ 10 | if(i == 0) dp[i][j] = j; 11 | else if(j == 0) dp[i][j] = i; 12 | else if(word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1]; 13 | else dp[i][j] = 1 + min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]); 14 | } 15 | } 16 | return dp[n][m]; 17 | } 18 | }; -------------------------------------------------------------------------------- /Cpp/edit-distance/solution2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int dfs(int i, int j, string &s, string &t, vector> &dp) { 3 | if(j == 0) return i; 4 | if(i == 0) return j; 5 | if(dp[i][j] != -1) return dp[i][j]; 6 | 7 | if(s[i - 1] == t[j - 1]) return dp[i][j] = dfs(i - 1, j - 1, s, t, dp); 8 | return dp[i][j] = 1 + min(dfs(i - 1, j - 1, s, t, dp), min(dfs(i, j - 1, s, t, dp), dfs(i - 1, j, s, t, dp))); 9 | } 10 | public: 11 | int minDistance(string s, string t) { 12 | int n = s.size(), m = t.size(); 13 | vector> dp(n + 1, vector(m + 1, -1)); 14 | 15 | return dfs(n, m, s, t, dp); 16 | } 17 | }; -------------------------------------------------------------------------------- /Cpp/equality-in-a-array/problem.md: -------------------------------------------------------------------------------- 1 | ## Equality in a Array 2 | 3 | Given an array of integers, determine the minimum number of elements to delete to leave only elements of equal value. 4 | 5 | #### Example 6 | 7 | `arr = [1, 2, 2, 3]` 8 | 9 | Delete the `2` elements `1` and `3` leaving `arr = [2, 2]`. If both twos plus either the `1` or the `3` are deleted, it takes `3` deletions to leave either `[3]` or `[1]`. The minimum number of deletions is `2`. 10 | 11 | #### Function Description 12 | 13 | equalizeArray has the following parameter(s): 14 | 15 | - `int arr[n]`: an array of integers 16 | 17 | #### Returns 18 | 19 | - `int`: the minimum number of deletions required 20 | 21 | #### Input Format 22 | 23 | - The first line contains an integer `n`, the number of elements in `arr`. 24 | - The next line contains `n` space-separated integers `arr[i]`. 25 | 26 | #### Constraints 27 | 28 | - `1 <= n <= 100` 29 | - `1 <= arr[i] <= 100` 30 | -------------------------------------------------------------------------------- /Cpp/equality-in-a-array/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int equalizeArray(vector arr) 7 | { 8 | map mp; 9 | int mx = 0; 10 | for (int el : arr) 11 | { 12 | mp[el]++; 13 | if (mp[el] > mx) 14 | mx = mp[el]; 15 | } 16 | return arr.size() - mx; 17 | } 18 | 19 | int main() 20 | { 21 | int n; 22 | cout << "Size: "; 23 | cin >> n; 24 | 25 | vector arr(n); 26 | for (int i = 0; i < n; i++) 27 | { 28 | cout << "Enter elements: "; 29 | cin >> arr[i]; 30 | } 31 | 32 | int result = equalizeArray(arr); 33 | cout << "Result: " << result << endl; 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Cpp/find-digits/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findDigits(int n) 5 | { 6 | int count = 0; 7 | int number = n; 8 | while (n > 0) 9 | { 10 | int d = n % 10; 11 | if (d != 0 && number % d == 0) 12 | count++; 13 | 14 | n /= 10; 15 | } 16 | 17 | return count; 18 | } 19 | 20 | int main() 21 | { 22 | int t; 23 | cout << "Number of test cases: "; 24 | cin >> t; 25 | 26 | while (t--) 27 | { 28 | int n; 29 | cout << "Number of digits: "; 30 | cin >> n; 31 | 32 | int result = findDigits(n); 33 | cout << "Result: " << result << endl; 34 | } 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Cpp/find-max-average/problem.md: -------------------------------------------------------------------------------- 1 | ## Find Max Average 2 | 3 | You are given an integer array `nums` consisting of `n` elements, and an integer `k`. 4 | 5 | Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return this value. Any answer with a calculation error less than `10^-5` will be accepted. 6 | 7 | #### Example 1: 8 | 9 | - Input: nums = [1,12,-5,-6,50,3], k = 4 10 | - Output: 12.75000 11 | - Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 12 | 13 | #### Example 2: 14 | 15 | - Input: nums = [5], k = 1 16 | - Output: 5.00000 17 | 18 | Constraints: 19 | 20 | - `n == nums.length` 21 | - `1 <= k <= n <= 10^5` 22 | - `-10^4 <= nums[i] <= 10^4` 23 | -------------------------------------------------------------------------------- /Cpp/find-max-average/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | double findMaxAverage(vector &nums, int k) 6 | { 7 | double maxSum = 0, currSum = 0; 8 | 9 | int n = nums.size(); 10 | 11 | for (int i = 0; i < k; i++) 12 | currSum += nums[i]; 13 | 14 | maxSum = currSum; 15 | 16 | for (int i = k; i < n; i++) 17 | { 18 | currSum += nums[i] - nums[i - k]; 19 | maxSum = max(maxSum, currSum); 20 | } 21 | 22 | return (maxSum / k); 23 | } 24 | 25 | int main() 26 | { 27 | int size, k; 28 | 29 | cout << "Size: "; 30 | cin >> size; 31 | 32 | vector nums(size); 33 | for (int i = 0; i < size; i++) 34 | { 35 | cout << "Enter elements: "; 36 | cin >> nums[i]; 37 | } 38 | 39 | cout << "Value of k: "; 40 | cin >> k; 41 | 42 | double result = findMaxAverage(nums, k); 43 | cout << "Result: " << result << endl; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Cpp/find-the-duplicate/problem.md: -------------------------------------------------------------------------------- 1 | Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. 2 | 3 | There is only one repeated number in nums, return this repeated number. 4 | 5 | You must solve the problem without modifying the array nums and uses only constant extra space. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: nums = [1,3,4,2,2] 12 | Output: 2 13 | -------------------------------------------------------------------------------- /Cpp/find-the-duplicate/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int findDuplicate(std::vector& nums) { 6 | std::unordered_set seen; 7 | 8 | for (int num : nums) { 9 | if (seen.count(num) > 0) { 10 | return num; // Found a duplicate 11 | } 12 | seen.insert(num); 13 | } 14 | 15 | return -1; // No duplicate found 16 | } 17 | 18 | int main() { 19 | std::vector nums = {1, 3, 4, 2, 2}; 20 | int duplicate = findDuplicate(nums); 21 | 22 | if (duplicate != -1) { 23 | std::cout << "Duplicate number: " << duplicate << std::endl; 24 | } else { 25 | std::cout << "No duplicate found." << std::endl; 26 | } 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Cpp/group-anagrams/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> groupAnagrams(vector& strs) { 4 | map> mp; 5 | vector> ans; 6 | for (int i = 0; i < strs.size(); i++) 7 | { 8 | string tem = strs[i]; 9 | sort(tem.begin(), tem.end()); 10 | mp[tem].push_back(strs[i]); 11 | } 12 | for(auto it: mp) 13 | { 14 | ans.push_back(it.second); 15 | } 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /Cpp/is-subsequence/problem.md: -------------------------------------------------------------------------------- 1 | ## Is Subsequence 2 | 3 | Given two strings `s` and `t`, return `true` if `s` is a **_subsequence_** of `t`, or `false` otherwise. 4 | 5 | A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace"` is a subsequence of `"abcde"` while `"aec"` is not). 6 | 7 | #### Example 1: 8 | 9 | - Input: s = "abc", t = "ahbgdc" 10 | - Output: true 11 | 12 | #### Example 2: 13 | 14 | - Input: s = "axc", t = "ahbgdc" 15 | - Output: false 16 | 17 | #### Constraints: 18 | 19 | - `0 <= s.length <= 100` 20 | - `0 <= t.length <= 104` 21 | - `s` and `t` consist only of lowercase English letters. 22 | -------------------------------------------------------------------------------- /Cpp/is-subsequence/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isSubsequence(string s, string t) 5 | { 6 | int i = 0, j = 0; 7 | 8 | while (i < s.length() && j < t.length()) 9 | { 10 | if (s[i] == t[j]) 11 | i++; 12 | 13 | j++; 14 | } 15 | return i == s.length(); 16 | } 17 | 18 | int main() 19 | { 20 | string s = "abc"; 21 | string t = "ahbgdc"; 22 | 23 | bool result = isSubsequence(s, t); 24 | cout << "Result: " << result << endl; 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Cpp/jumping-on-the-clouds/solution-2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int jumpingOnClouds(vector c, int n) 6 | { 7 | int jumps = 0; // Initialize number of jumps 8 | int i = 0; // Initialize current position index 9 | 10 | // Continue until the last cloud is reached 11 | while (i < n - 1) 12 | { 13 | // Check if jumping 2 steps is possible and safe 14 | if (i + 2 < n && c[i + 2] == 0) 15 | i += 2; 16 | else 17 | i += 1; 18 | 19 | // Increment the jump count 20 | jumps++; 21 | } 22 | 23 | return jumps; 24 | } 25 | 26 | int main() 27 | { 28 | int n; 29 | cout << "Enter size: "; 30 | cin >> n; 31 | 32 | vector clouds(n); 33 | for (int i = 0; i < n; i++) 34 | { 35 | cout << "Enter binary values: "; 36 | cin >> clouds[i]; 37 | } 38 | 39 | int result = jumpingOnClouds(clouds, n); 40 | cout << "Minimum number of jumps: " << result << endl; 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Cpp/jumping-on-the-clouds/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int jumpingOnClouds(vector c, int k) 6 | { 7 | int e = 100; // Initial Energy(e) 8 | int i = 0; // Initial starting position 9 | 10 | do 11 | { 12 | i = (i + k) % c.size(); // Calculate the next position in the array 13 | e -= 1; 14 | 15 | // Check if the value in the array is `1 (thunderheads)`. 16 | if (c[i] == 1) 17 | e -= 2; 18 | } while (i != 0); 19 | 20 | return e; 21 | } 22 | 23 | int main() 24 | { 25 | int n; 26 | cout << "Enter number of Clouds: "; 27 | cin >> n; 28 | 29 | vector c(n); 30 | for (int i = 0; i < n; i++) 31 | { 32 | cout << "Enter types of cloud: "; 33 | cin >> c[i]; 34 | } 35 | 36 | int k; 37 | cout << "Enter length of one jump: "; 38 | cin >> k; 39 | 40 | int result = jumpingOnClouds(c, k); 41 | cout << "Result: " << result << endl; 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /Cpp/kids-with-the-greatest-number-of-candies/problem.md: -------------------------------------------------------------------------------- 1 | ## Kids with the greatest number of candies 2 | 3 | There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. 4 | 5 | Return a boolean array result of length `n`, where `result[i]` is **true** if, after giving the `ith` kid all the `extraCandies`, they will have the **greatest** number of candies among all the kids, or **false** otherwise. 6 | 7 | Note that **multiple** kids can have the **greatest** number of candies. 8 | -------------------------------------------------------------------------------- /Cpp/kokoEatingBananas/problem.md: -------------------------------------------------------------------------------- 1 | #Problem no.:Leetcode-Medium 875(Koko Eating bananas) 2 | 3 | Problem Statement: A monkey is given ‘n’ piles of bananas, whereas the ‘ith’ pile has ‘a[i]’ bananas. An integer ‘h’ is also given, which denotes the time (in hours) for all the bananas to be eaten. 4 | 5 | Each hour, the monkey chooses a non-empty pile of bananas and eats ‘k’ bananas. If the pile contains less than ‘k’ bananas, then the monkey consumes all the bananas and won’t eat any more bananas in that hour. 6 | 7 | Find the minimum number of bananas ‘k’ to eat per hour so that the monkey can eat all the bananas within ‘h’ hours. 8 | 9 | Example 1: 10 | Input Format: N = 4, a[] = {7, 15, 6, 3}, h = 8 11 | Result: 5 12 | Explanation: If Koko eats 5 bananas/hr, he will take 2, 3, 2, and 1 hour to eat the piles accordingly. So, he will take 8 hours to complete all the piles. -------------------------------------------------------------------------------- /Cpp/largest-rectangle-in-histogram/problem.md: -------------------------------------------------------------------------------- 1 | Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | 8 | Input: heights = [2,1,5,6,2,3] 9 | Output: 10 10 | Explanation: The above is a histogram where width of each bar is 1. 11 | The largest rectangle is shown in the red area, which has an area = 10 units. 12 | Example 2: 13 | 14 | 15 | Input: heights = [2,4] 16 | Output: 4 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= heights.length <= 10^5 22 | 0 <= heights[i] <= 10^4 -------------------------------------------------------------------------------- /Cpp/largest-rectangle-in-histogram/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestRectangleArea(vector& heights) { 4 | int n = heights.size(); 5 | stack st; 6 | int res=0; 7 | int i=0; 8 | while(i 2 | using namespace std; 3 | 4 | string lengthOfLastWord(string s) 5 | { 6 | int length = 0; 7 | int i = s.length() - 1; 8 | 9 | // Check if there is any space, skip the trailing space. 10 | while (i >= 0 && s[i] == ' ') 11 | i--; 12 | 13 | // Count the length of the word. 14 | while (i >= 0 && s[i] != ' ') 15 | { 16 | length++; 17 | i--; 18 | } 19 | 20 | cout << "Length of the last word: " << length << endl; 21 | } 22 | 23 | int main() 24 | { 25 | string str = "Hello World"; 26 | lengthOfLastWord(str); 27 | return 0; 28 | } -------------------------------------------------------------------------------- /Cpp/longest-common-prefix/problem.md: -------------------------------------------------------------------------------- 1 | ## Longest Common Prefix 2 | 3 | Write a function to find the longest common prefix string amongst an array of strings. 4 | 5 | If there is no common prefix, return an empty string `""`. 6 | 7 | #### Constraints: 8 | 9 | - `1 <= strs.length <= 200` 10 | - `0 <= strs[i].length <= 200` 11 | - `strs[i]` consists of only lowercase English letters. 12 | -------------------------------------------------------------------------------- /Cpp/longest-consecutive-sequence/problem.md: -------------------------------------------------------------------------------- 1 | ## Longest Consecutive Sequence 2 | 3 | Given an unsorted array of integers **nums**, return the length of the longest consecutive elements sequence. 4 | 5 | You must write an algorithm that runs in O(n) time. 6 | -------------------------------------------------------------------------------- /Cpp/majority-element/problem.md: -------------------------------------------------------------------------------- 1 | ## Find Majority Element 2 | 3 | - Given an integer array of size _n_, find all elements that appear more than **[ n/3 ] times**. 4 | -------------------------------------------------------------------------------- /Cpp/maximum-product-subarray/problem.md: -------------------------------------------------------------------------------- 1 | # Maximum Product Subarray 2 | 3 | ## Problem Description 4 | 5 | Given an integer array `nums`, your task is to find a subarray that has the largest product, and return that product. A subarray is defined as a contiguous part of an array. 6 | 7 | The test cases are generated such that the answer will fit in a 32-bit integer. 8 | 9 | ## Objective 10 | 11 | Return the maximum product of any subarray within the given integer array `nums`. 12 | 13 | --- 14 | 15 | ### Constraints 16 | 17 | - `1 <= nums.length <= 20,000` 18 | - `-10 <= nums[i] <= 10` 19 | - The product of any subarray of `nums` is guaranteed to fit in a 32-bit integer. 20 | 21 | --- 22 | 23 | ### Examples 24 | 25 | **Input 1:** 26 | 27 | ```plaintext 28 | nums = [2, 3, -2, 4] 29 | ``` 30 | 31 | **Output 1:** 32 | 33 | ```plaintext 34 | 6 35 | ``` 36 | 37 | **Input 2:** 38 | 39 | ```plaintext 40 | nums = [-2,0,-1] 41 | ``` 42 | 43 | **Output 2:** 44 | 45 | ```plaintext 46 | 0 47 | ``` 48 | -------------------------------------------------------------------------------- /Cpp/maximum-subarray/problem.md: -------------------------------------------------------------------------------- 1 | ## Maximum SubArray 2 | 3 | - Given an integer array **nums**, find the **subarray** with the largest sum, and return its sum. 4 | -------------------------------------------------------------------------------- /Cpp/maximum-subarray/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int maxSubArray(vector &nums) 6 | { 7 | int maxEndingHere = nums[0]; 8 | int maxSoFar = nums[0]; 9 | 10 | for (int i = 1; i < nums.size(); i++) 11 | { 12 | maxEndingHere = max(nums[i], maxEndingHere + nums[i]); 13 | maxSoFar = max(maxSoFar, maxEndingHere); 14 | } 15 | 16 | return maxSoFar; 17 | } 18 | 19 | int main() 20 | { 21 | int n; 22 | cout << "Enter Size: "; 23 | cin >> n; 24 | 25 | vector nums(n); 26 | 27 | for (int i = 0; i < n; i++) 28 | { 29 | cout << "Enter elements: "; 30 | cin >> nums[i]; 31 | } 32 | 33 | int result = maxSubArray(nums); 34 | cout << "Result: " << result << endl; 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Cpp/merge-sorted-array/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void merge(vector nums1, int m, vector nums2, int n) 7 | { 8 | int i = m - 1; 9 | int j = n - 1; 10 | int k = m + n - 1; 11 | 12 | while (j >= 0) 13 | { 14 | if (i >= 0 && nums1[i] > nums2[j]) 15 | nums1[k--] = nums1[i--]; 16 | else 17 | nums1[k--] = nums2[j--]; 18 | } 19 | 20 | cout << "["; 21 | for (int i = 0; i < (m + n); ++i) 22 | { 23 | cout << nums1[i]; 24 | if (i < (m + n) - 1) 25 | { 26 | cout << ", "; 27 | } 28 | } 29 | cout << "]"; 30 | } 31 | 32 | int main() 33 | { 34 | vector nums1 = {1, 2, 3, 0, 0, 0}; 35 | int m = 3; 36 | 37 | vector nums2 = {2, 5, 6}; 38 | int n = 3; 39 | 40 | merge(nums1, m, nums2, n); 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Cpp/merge-strings/problem.md: -------------------------------------------------------------------------------- 1 | You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. 2 | 3 | Return the merged string. 4 | -------------------------------------------------------------------------------- /Cpp/merge-strings/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void mergeString(string s1, string s2) 5 | { 6 | cout << "into the function" << endl; 7 | string result = ""; 8 | int i; 9 | for (i = 0; i < s1.length() || i < s2.length(); i++) 10 | { 11 | if (i < s1.length()) 12 | result += s1[i]; 13 | 14 | if (i < s2.length()) 15 | result += s2[i]; 16 | } 17 | } 18 | 19 | int main() 20 | { 21 | string s1 = "jenil"; 22 | string s2 = "gajjar"; 23 | mergeString(s1, s2); 24 | return 0; 25 | } -------------------------------------------------------------------------------- /Cpp/migratory-birds/problem.md: -------------------------------------------------------------------------------- 1 | ## Migratory Birds 2 | 3 | Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than `1` type has been spotted that maximum amount, return the smallest of their ids. 4 | 5 | #### Example 6 | 7 | ``` 8 | arr = [1, 1, 2, 3, 3] 9 | ``` 10 | 11 | There are two each of types `1` and `2`, and one sighting of type `3`. Pick the lower of the two types seen twice: type `1`. 12 | 13 | #### Function Description 14 | 15 | The function has the following parameter(s): 16 | 17 | - `int arr[n]`: the types of birds sighted. 18 | 19 | #### Returns 20 | 21 | - `int`: the lowest type id of the most frequently sighted birds. 22 | 23 | #### Input Format 24 | 25 | - The first line contains an integer, `n` the size of `arr`. 26 | - The second line describes `arr` as `n` space-separated integers, each a type number of the bird sighted. 27 | 28 | #### Constraints 29 | 30 | - `5 <= n <= 2 x 10^5` 31 | - It is guaranteed that each type is `1`, `2`, `3`, `4`, or `5`. 32 | -------------------------------------------------------------------------------- /Cpp/migratory-birds/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int migratoryBirds(vector &arr) 7 | { 8 | int maxCount = 0; 9 | int mostFrequentBirds = 1; 10 | map birdCount; 11 | 12 | for (int bird : arr) 13 | birdCount[bird]++; 14 | 15 | for (auto &entry : birdCount) 16 | { 17 | if (entry.second > maxCount) 18 | { 19 | maxCount = entry.second; 20 | mostFrequentBirds = entry.first; 21 | } 22 | } 23 | 24 | return mostFrequentBirds; 25 | } 26 | 27 | int main() 28 | { 29 | int n; 30 | cout << "Enter size: "; 31 | cin >> n; 32 | 33 | vector arr(n); 34 | for (int i = 0; i < n; i++) 35 | { 36 | cout << "Enter elements: "; 37 | cin >> arr[i]; 38 | } 39 | 40 | int result = migratoryBirds(arr); 41 | cout << "Result: " << result << endl; 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Cpp/min-max-sum/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int minMaxSum(int arr[], int n) 6 | { 7 | // Sorting the array integers 8 | sort(arr, arr + n); 9 | 10 | long max = 0; 11 | long min = 0; 12 | int i; 13 | for (i = 0; i < n - 1; i++) 14 | min += arr[i]; 15 | 16 | for (i = 1; i < n; i++) 17 | max += arr[i]; 18 | 19 | cout << min << " " << max << endl; 20 | } 21 | 22 | int main() 23 | { 24 | int n; 25 | cout << "Enter size: "; 26 | cin >> n; // Taking size as input 27 | 28 | int arr[n]; 29 | 30 | for (int i = 0; i < n; i++) 31 | { 32 | cout << "Input value: "; 33 | cin >> arr[i]; 34 | } 35 | 36 | minMaxSum(arr, n); 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Cpp/move-zeros/problem.md: -------------------------------------------------------------------------------- 1 | ## Move Zeros 2 | 3 | Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. 4 | 5 | Note that you must do this in-place without making a copy of the array. 6 | 7 | #### Example 1: 8 | 9 | - Input: nums = [0,1,0,3,12] 10 | - Output: [1,3,12,0,0] 11 | 12 | #### Example 2: 13 | 14 | - Input: nums = [0] 15 | - Output: [0] 16 | 17 | #### Constraints: 18 | 19 | - `1 <= nums.length <= 104` 20 | - `-231 <= nums[i] <= 231 - 1` 21 | -------------------------------------------------------------------------------- /Cpp/move-zeros/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void moveZeros(vector &nums) 7 | { 8 | int n = nums.size(); 9 | 10 | int i = 0; 11 | for (int j = 0; j < n; j++) 12 | { 13 | if (nums[j] != 0) 14 | { 15 | swap(nums[i], nums[j]); 16 | i++; 17 | } 18 | } 19 | 20 | for (int k = 0; k < n; k++) 21 | cout << "Nums: " << nums[k] << endl; 22 | } 23 | 24 | int main() 25 | { 26 | vector nums = {0, 1, 0, 3, 12}; 27 | moveZeros(nums); 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /Cpp/next-permutation/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int nextPermutation(vector &nums, int n) 7 | { 8 | int i = n - 2; 9 | 10 | while (i >= 0 && nums[i] >= nums[i + 1]) 11 | i--; 12 | 13 | if (i >= 0) 14 | { 15 | int j = n - 1; 16 | 17 | while (j > 1 && nums[j] <= nums[i]) 18 | j--; 19 | 20 | swap(nums[i], nums[j]); 21 | } 22 | 23 | reverse(nums.begin() + i + 1, nums.end()); 24 | } 25 | 26 | int main() 27 | { 28 | int size; 29 | cout << "Enter Size: "; 30 | cin >> size; 31 | 32 | vector nums(size); 33 | 34 | for (int i = 0; i < size; i++) 35 | { 36 | cout << "Enter elements: "; 37 | cin >> nums[i]; 38 | } 39 | 40 | nextPermutation(nums, size); 41 | 42 | for (int num : nums) 43 | cout << num << " "; 44 | 45 | cout << endl; 46 | return 0; 47 | } -------------------------------------------------------------------------------- /Cpp/number-line-jumps/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | string kangaroo(int x1, int v1, int x2, int v2){ 6 | int count = 0; 7 | 8 | for(int i = 1; i <= 10000; i++){ 9 | if(x1 + (v1 * i) == x2 + (v2 * i)){ 10 | count += 1; 11 | break; 12 | } else continue; 13 | } 14 | 15 | if(count == 1) return "YES"; 16 | else return "NO"; 17 | } 18 | 19 | int main() 20 | { 21 | int x1 = 2; 22 | int v1 = 1; 23 | int x2 = 1; 24 | int v2 = 2; 25 | 26 | string result = kangaroo(x1, v1, x2, v2); 27 | cout << "Result: " << result << endl; 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /Cpp/palindrome-number/problem.md: -------------------------------------------------------------------------------- 1 | ## Palindrome Number 2 | 3 | - Given an integer **_x_**, return true if **_x_** is a **palindrome**, and false otherwise. 4 | -------------------------------------------------------------------------------- /Cpp/palindrome-number/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isPalindrome(int n) 5 | { 6 | // Negative numbers or equal to zero are not a palindrome numbers 7 | if (n < 0 || (n % 10 == 0 && n != 0)) 8 | return false; 9 | 10 | int reverseHalf = 0; 11 | while (n > reverseHalf) 12 | { 13 | reverseHalf = reverseHalf * 10 + n % 10; 14 | n /= 10; 15 | } 16 | 17 | return n == reverseHalf || n == reverseHalf / 10; 18 | } 19 | 20 | int main() 21 | { 22 | int n; // n is the number 23 | cout << "Input any number: "; 24 | cin >> n; 25 | 26 | bool result = isPalindrome(n); 27 | if (result) 28 | cout << "Number " << n << " is Palindrome"; 29 | else 30 | cout << "Number " << n << " is not Palindrome"; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Cpp/pascals-triangle/problem.md: -------------------------------------------------------------------------------- 1 | Given an integer **numRows**, return the first numRows of Pascal's triangle. 2 | 3 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 4 | 5 | pascals-triangle 6 | 7 | The value can be calculated using following formula: **C(i, j) = i! / ((i-j)! \* i!)** 8 | -------------------------------------------------------------------------------- /Cpp/pascals-triangle/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binoCoff(int l, int k) 5 | { 6 | int res = 1; 7 | if (k > l - k) 8 | k = l - k; 9 | 10 | for (int i = 0; i < k; i++) 11 | { 12 | res *= (l - i); 13 | res /= (i + 1); 14 | } 15 | return res; 16 | } 17 | 18 | void pascalTriangle(int n) 19 | { 20 | int i; 21 | int j; 22 | 23 | for (i = 0; i < n; i++) // Iterate through every line of the triangle. 24 | { 25 | for (j = 0; j <= i; j++) // Every line number is equal to the number of intergers. 26 | { 27 | cout << " " << binoCoff(i, j); 28 | } 29 | cout << "\n"; 30 | } 31 | } 32 | 33 | int main() 34 | { 35 | int n; 36 | cout << "Enter number of rows: "; 37 | cin >> n; // Taking n (number of rows) as an input. 38 | pascalTriangle(n); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Cpp/picking-numbers/problem.md: -------------------------------------------------------------------------------- 1 | ## Picking Numbers 2 | 3 | Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to `1`. 4 | 5 | #### Example 6 | 7 | `a = [1, 1, 2, 2, 4, 4, 5, 5, 5]` 8 | 9 | There are two sub-arrays meeting the criterion: `[1, 1, 2, 2]` and `[4, 4, 5, 5, 5]`. The maximum length sub-array has `5` elements. 10 | 11 | #### Function Description 12 | 13 | pickingNumbers has the following parameter(s): 14 | 15 | - `int a[n]`: an array of integers 16 | 17 | #### Returns 18 | 19 | - `int`: the length of the longest sub-array that meets the criterion 20 | 21 | #### Input Format 22 | 23 | - The first line contains a single integer `n`, the size of the array `a`. 24 | - The second line contains `n` space-separated integers, each an `a[i]`. 25 | 26 | #### Constraints 27 | 28 | - `2 <= n <= 100`. 29 | - `0 < a[i] < 100`. 30 | - The answer will be `>= 2`. 31 | -------------------------------------------------------------------------------- /Cpp/picking-numbers/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int pickingNumbers(vector arr) 6 | { 7 | vector count(100, 0); 8 | 9 | for (int num : arr) 10 | count[num]++; 11 | 12 | int maxLength = 0; 13 | 14 | for (int i = 1; i < 100; i++) 15 | maxLength = max(maxLength, count[i] + count[i - 1]); 16 | 17 | return maxLength; 18 | } 19 | 20 | int main() 21 | { 22 | int size; 23 | cout << "Enter size: "; 24 | cin >> size; 25 | 26 | vector arr(size); 27 | for (int i = 0; i < size; i++) 28 | { 29 | cout << "Enter elements: "; 30 | cin >> arr[i]; 31 | } 32 | 33 | int result = pickingNumbers(arr); 34 | cout << "Result: " << result << endl; 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /Cpp/plus-one/problem.md: -------------------------------------------------------------------------------- 1 | ## Plus One 2 | 3 | You are given a **large integer** represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s. 4 | 5 | Increment the large integer by **one** and return the resulting array of `digits`. 6 | 7 | #### Constraints: 8 | 9 | - `1 <= digits.length <= 100` 10 | - `0 <= digits[i] <= 9` 11 | - `digits` does not contain any leading `0`'s. 12 | -------------------------------------------------------------------------------- /Cpp/plus-one/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | vector plusOne(vector &digits) 6 | { 7 | int i; 8 | int size = digits.size(); 9 | 10 | for (i = size - 1; i >= 0; i--) 11 | { 12 | // Check if the value equal 9. 13 | if (digits[i] == 9) 14 | digits[i] = 0; 15 | // Check if the value id less than 9, then increment that value by 1. 16 | else 17 | { 18 | digits[i]++; 19 | return digits; 20 | } 21 | } 22 | 23 | digits.insert(digits.begin(), 1); 24 | return digits; 25 | } 26 | 27 | int main() 28 | { 29 | vector digits = {9}; 30 | 31 | vector result = plusOne(digits); 32 | 33 | for (int num : result) 34 | cout << "Num: " << num << endl; 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /Cpp/product_of_numbers/problem.md: -------------------------------------------------------------------------------- 1 | # Product of numbers in Array except number i 2 | Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. 3 | For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. 4 | -------------------------------------------------------------------------------- /Cpp/product_of_numbers/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | std::vector multiplier(std::vector input); 5 | 6 | int main() 7 | { 8 | std::vector test = {1, 2, 3, 4, 5}; 9 | std::vector output_test = multiplier(test); 10 | for(int i = 0; i < output_test.size(); i++) 11 | { 12 | std::cout << output_test[i]<<"\n"; 13 | } 14 | 15 | return 0; 16 | } 17 | 18 | std::vector multiplier(std::vector input) 19 | { 20 | int n = input.size(); 21 | std::vector output; 22 | 23 | 24 | for(int i = 0; i < n; i++) 25 | { 26 | int result = 1; 27 | for(int p = 0; p < n; p++) 28 | { 29 | if(i == p) 30 | { 31 | continue; 32 | } 33 | result *= input[p]; 34 | } 35 | output.push_back(result); 36 | } 37 | return output; 38 | } 39 | -------------------------------------------------------------------------------- /Cpp/rearrange-substrings/problem.md: -------------------------------------------------------------------------------- 1 | # Count Substrings That Can Be Rearranged to Contain a String II 2 | 3 | ## Problem Description 4 | 5 | You are given two strings, `word1` and `word2`. Your task is to count all possible substrings of `word1` that can be rearranged to contain `word2` as a subsequence. 6 | 7 | In other words, for each substring of `word1`, if you can rearrange its characters to form a string that contains `word2` as a subsequence, then this substring is considered valid. The order of characters in `word2` should be preserved within the rearranged substring. 8 | 9 | ## Objective 10 | 11 | Return the total number of such valid substrings of `word1` that meet the requirement of containing `word2` as a subsequence. The answer may be large, so return it as a 64-bit integer. 12 | 13 | --- 14 | 15 | ### Constraints 16 | 17 | - `1 <= word1.length, word2.length <= 1000` 18 | - `word1` and `word2` consist only of lowercase English letters. 19 | 20 | ### Example 21 | 22 | **Input** 23 | ```plaintext 24 | word1 = "abcabc", word2 = "abc" 25 | ``` 26 | 27 | **Output** 28 | ```plaintext 29 | 10 30 | ``` -------------------------------------------------------------------------------- /Cpp/remove-element/problem.md: -------------------------------------------------------------------------------- 1 | ## Remove Element 2 | 3 | Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` **in-place**. The order of the elements may be changed. Then return the number of elements in `nums` which are not equal to `val`. 4 | 5 | Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things: 6 | 7 | - Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. 8 | - The remaining elements of `nums` are not important as well as the size of `nums`. 9 | - Return `k`. 10 | 11 | #### Constraints: 12 | 13 | - `0 <= nums.length <= 100` 14 | - `0 <= nums[i] <= 50` 15 | - `0 <= val <= 100` 16 | -------------------------------------------------------------------------------- /Cpp/remove-element/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int removeElement(int nums[], int val, int size) 5 | { 6 | int k = 0; 7 | 8 | for (int i = 0; i < size; i++) 9 | { 10 | if (nums[i] != val) 11 | { 12 | nums[k] = nums[i]; 13 | k++; 14 | } 15 | } 16 | return k; 17 | } 18 | 19 | int main() 20 | { 21 | int nums[] = {3, 2, 2, 3}; 22 | int size = sizeof(nums) / sizeof(nums[0]); 23 | int val = 2; 24 | 25 | int newSize = removeElement(nums, val, size); 26 | cout << "New Size of nums after removing " << val << ": " << newSize << endl; 27 | 28 | for (int i = 0; i < newSize; i++) 29 | cout << "==> " << nums[i] << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Cpp/repeated-strings/problem.md: -------------------------------------------------------------------------------- 1 | ## Repeated Strings 2 | 3 | There is a string, `s`, of lowercase English letters that is repeated infinitely many times. Given an integer, `n`, find and print the number of letter a's in the first `n` letters of the infinite string. 4 | 5 | #### Example 6 | 7 | ``` 8 | s = 'abcac' 9 | n = 10 10 | ``` 11 | 12 | The substring we consider is `abcacabcac`, the first `10` characters of the infinite string. There are `4` occurrences of **a** in the substring. 13 | 14 | #### Function Description 15 | 16 | repeatedString has the following parameter(s): 17 | 18 | - `s`: a string to repeat 19 | - `n`: the number of characters to consider 20 | 21 | #### Returns 22 | 23 | - `int`: the frequency of a in the substring 24 | 25 | #### Input Format 26 | 27 | - The first line contains a single string, `s`. 28 | - The second line contains an integer, `n`. 29 | 30 | #### Constraints 31 | 32 | - `1 <= |s| <= 100` 33 | - `1 <= n <= 10^12` 34 | - For `25%` of the test cases, `n <= 10^6`. 35 | -------------------------------------------------------------------------------- /Cpp/repeated-strings/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | long repeatedString(string s, int n) 5 | { 6 | int count_a = 0; 7 | 8 | for (int i = 0; i < s.length(); i++) 9 | { 10 | if (s[i] == 'a') 11 | count_a++; 12 | } 13 | 14 | long repeat_count = n / s.length(); 15 | long total_a_count = repeat_count * count_a; 16 | 17 | long remaining_chars = n % s.length(); 18 | for (int i = 0; i < remaining_chars; i++) 19 | { 20 | if (s[i] == 'a') 21 | total_a_count++; 22 | } 23 | 24 | return total_a_count; 25 | } 26 | 27 | int main() 28 | { 29 | string s; 30 | cout << "Enter string: "; 31 | cin >> s; 32 | 33 | int n; 34 | cout << "Enter n: "; 35 | cin >> n; 36 | 37 | long result = repeatedString(s, n); 38 | cout << "Result: " << result << endl; 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /Cpp/reverse-integer/problem.md: -------------------------------------------------------------------------------- 1 | Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. 2 | 3 | Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: x = 123 10 | Output: 321 -------------------------------------------------------------------------------- /Cpp/reverse-integer/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int reverseInteger(int x) { 4 | int reversed = 0; 5 | 6 | while (x != 0) { 7 | int digit = x % 10; 8 | x /= 10; 9 | 10 | // Check for integer overflow/underflow 11 | if (reversed > INT_MAX / 10 || (reversed == INT_MAX / 10 && digit > 7)) return 0; 12 | if (reversed < INT_MIN / 10 || (reversed == INT_MIN / 10 && digit < -8)) return 0; 13 | 14 | reversed = reversed * 10 + digit; 15 | } 16 | 17 | return reversed; 18 | } 19 | 20 | int main() { 21 | int num = 12345; 22 | int reversedNum = reverseInteger(num); 23 | 24 | std::cout << "Original: " << num << std::endl; 25 | std::cout << "Reversed: " << reversedNum << std::endl; 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Cpp/reverse-vowels/problem.md: -------------------------------------------------------------------------------- 1 | # Reverse Vowels of a String 2 | 3 | Given a string `s`, reverse only all the vowels in the string and return it. 4 | 5 | The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once. 6 | 7 | #### Example 1: 8 | 9 | - Input: s = "hello" 10 | - Output: "holle" 11 | 12 | #### Example 2: 13 | 14 | - Input: s = "leetcode" 15 | - Output: "leotcede" 16 | 17 | #### Constraints: 18 | 19 | - `1 <= s.length <= 3 x 10^5` 20 | - `s` consist of **printable ASCII** characters. 21 | -------------------------------------------------------------------------------- /Cpp/reverse-vowels/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | string reverseVowels(string s) 5 | { 6 | 7 | int left = 0; 8 | int right = s.length() - 1; 9 | 10 | string vowels = "aeiouAEIOU"; 11 | 12 | while (left < right) 13 | { 14 | while (left < right && vowels.find(s[left]) == -1) 15 | left++; 16 | 17 | while (left < right && vowels.find(s[right]) == -1) 18 | right--; 19 | 20 | swap(s[left], s[right]); 21 | 22 | left++; 23 | right--; 24 | } 25 | 26 | return s; 27 | } 28 | 29 | int main() 30 | { 31 | string str; 32 | cout << "Enter string: "; 33 | cin >> str; 34 | 35 | string result = reverseVowels(str); 36 | cout << "Result: " << result << endl; 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /Cpp/reverse-words-in-a-string/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | string reverseWords(string s) 8 | { 9 | istringstream iss(s); 10 | vector words; 11 | 12 | while (iss >> s) 13 | words.push_back(s); 14 | 15 | reverse(words.begin(), words.end()); 16 | 17 | string result; 18 | for (string word : words) 19 | result += word + " "; 20 | 21 | if (!result.empty()) 22 | result.pop_back(); 23 | 24 | return result; 25 | } 26 | 27 | int main() 28 | { 29 | string s = "hello world"; 30 | 31 | cout << reverseWords(s); 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Cpp/sales-by-match/problem.md: -------------------------------------------------------------------------------- 1 | ## Sales by Match 2 | 3 | There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. 4 | 5 | #### Example 6 | 7 | ``` 8 | n = 7 9 | ar = [1, 2, 1, 2, 1, 3, 2] 10 | ``` 11 | 12 | There is one pair of color `1` and one of color `2`. There are three odd socks left, one of each color. The number of pairs is `2`. 13 | 14 | #### Function Description 15 | 16 | The function has the following parameter(s): 17 | 18 | - `int n`: the number of socks in the pile 19 | - `int ar[n]`: the colors of each sock 20 | 21 | #### Returns 22 | 23 | - `int`: the number of pairs 24 | 25 | #### Input Format 26 | 27 | - The first line contains an integer `n` the number of socks represented in `ar`. 28 | - The second line contains `n` space-separated integers, `ar[i]`, the colors of the socks in the pile. 29 | 30 | #### Constraints 31 | 32 | - `1 <= n <= 100` 33 | - `1 <= ar[i] <= 100` where `0 <= i < n` 34 | -------------------------------------------------------------------------------- /Cpp/sales-by-match/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int sockMerchant(vector arr, int n) 7 | { 8 | int pairs = 0; 9 | unordered_map sockCount; 10 | 11 | for (int count : arr) 12 | sockCount[count]++; 13 | 14 | for (auto entry : sockCount) 15 | pairs += entry.second / 2; 16 | 17 | return pairs; 18 | } 19 | 20 | int main() 21 | { 22 | int size; 23 | cout << "Enter size: "; 24 | cin >> size; 25 | 26 | vector arr(size); 27 | for (int i = 0; i < size; i++) 28 | { 29 | cout << "Enter color of each sock: "; 30 | cin >> arr[i]; 31 | } 32 | 33 | int result = sockMerchant(arr, size); 34 | cout << "Number of pairs: " << result << endl; 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Cpp/save-the-prisoner/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int saveThePrisoner(int n, int m, int s) 5 | { 6 | int lastCandy = (s + m - 1) % n; 7 | 8 | if (lastCandy == 0) 9 | lastCandy = n; 10 | 11 | return lastCandy; 12 | } 13 | 14 | int main() 15 | { 16 | int t; 17 | cout << "Number of Test Cases: "; 18 | cin >> t; 19 | 20 | for (int i = 0; i < t; i++) 21 | { 22 | int n, m, s; 23 | 24 | cout << "Number of prisoners: "; 25 | cin >> n; 26 | 27 | cout << "Number of Sweets: "; 28 | cin >> m; 29 | 30 | cout << "Chair Number to start with: "; 31 | cin >> s; 32 | 33 | int result = saveThePrisoner(n, m, s); 34 | cout << "Result: " << result << endl; 35 | } 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Cpp/search-2d-matrix-(ii)/problem.md: -------------------------------------------------------------------------------- 1 | ## Search a 2D Matrix - ii 2 | 3 | Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties: 4 | 5 | - Integers in each row are sorted in ascending from left to right. 6 | - Integers in each column are sorted in ascending from top to bottom. 7 | 8 | #### Constraints: 9 | 10 | - `m == matrix.length` 11 | - `n == matrix[i].length` 12 | - `1 <= n, m <= 300` 13 | - `-10^9 <= matrix[i][j] <= 10^9` 14 | - All the integers in each row are **sorted** in ascending order. 15 | - All the integers in each column are **sorted** in ascending order. 16 | - `-10^9 <= target <= 10^9` 17 | -------------------------------------------------------------------------------- /Cpp/search-insert-position/problem.md: -------------------------------------------------------------------------------- 1 | ## Search Insert Position 2 | 3 | Given a sorted array of distinct integers 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. 4 | 5 | You must write an algorithm with `O(log n)` runtime complexity. 6 | 7 | #### Example 1: 8 | 9 | - Input: nums = [1,3,5,6], target = 5 10 | - Output: 2 11 | 12 | #### Example 2: 13 | 14 | - Input: nums = [1,3,5,6], target = 2 15 | - Output: 1 16 | 17 | #### Example 3: 18 | 19 | - Input: nums = [1,3,5,6], target = 7 20 | - Output: 4 21 | 22 | #### Constraints: 23 | 24 | - `1 <= nums.length <= 104` 25 | - `-104 <= nums[i] <= 104` 26 | - `nums` contains distinct values sorted in ascending order. 27 | - `-104 <= target <= 104` 28 | -------------------------------------------------------------------------------- /Cpp/search-insert-position/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int searchInsert(vector &nums, int target) 6 | { 7 | int low = 0, high = nums.size(); 8 | 9 | if (target > nums[high - 1]) 10 | return high; 11 | 12 | while (low <= high) 13 | { 14 | int mid = (low + high) / 2; 15 | 16 | if (target == nums[mid]) 17 | return mid; 18 | 19 | if (target < nums[mid]) 20 | high = mid - 1; 21 | else 22 | low = mid + 1; 23 | } 24 | return low; 25 | } 26 | 27 | int main() 28 | { 29 | int n, target; 30 | 31 | cout << "Size: "; 32 | cin >> n; 33 | 34 | vector nums(n); 35 | for (int i = 0; i < n; i++) 36 | { 37 | cout << "Enter Elements: "; 38 | cin >> nums[i]; 39 | } 40 | 41 | cout << "Target Value: "; 42 | cin >> target; 43 | 44 | int result = searchInsert(nums, target); 45 | cout << "Result: " << result << endl; 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /Cpp/sequence-equation/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | vector permutationEquation(vector p) 6 | { 7 | int size = p.size(); 8 | vector result(size); 9 | 10 | vector indexMap(size); 11 | for (int i = 0; i < size; i++) 12 | indexMap[p[i]] = i + 1; 13 | 14 | for (int x = 1; x <= size; x++) 15 | { 16 | int y = indexMap[indexMap[x]]; 17 | result[x - 1] = y; 18 | } 19 | 20 | return result; 21 | } 22 | 23 | int main() 24 | { 25 | int n; 26 | cout << "Enter size: "; 27 | cin >> n; 28 | 29 | vector p(n); 30 | for (int i = 0; i < n; i++) 31 | { 32 | cout << "Enter elements: "; 33 | cin >> p[i]; 34 | } 35 | 36 | vector result = permutationEquation(p); 37 | for (int res : result) 38 | cout << "Result: " << res << endl; 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /Cpp/sherlock-and-squares/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int squares(int a, int b) 6 | { 7 | int count = 0; 8 | 9 | // Find sqrt of a - 1 10 | int sqrt_a = sqrt(a - 1); 11 | 12 | // Find sqrt of b 13 | int sqrt_b = sqrt(b); 14 | 15 | // Get the difference between both 16 | count = sqrt_b - sqrt_a; 17 | 18 | return count; 19 | } 20 | 21 | int main() 22 | { 23 | int q; 24 | cout << "Test Cases: "; 25 | cin >> q; 26 | 27 | while (q--) 28 | { 29 | int a, b; 30 | 31 | cout << "a: "; 32 | cin >> a; 33 | 34 | cout << "b: "; 35 | cin >> b; 36 | 37 | int count = squares(a, b); 38 | cout << "Count: " << count << endl; 39 | } 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Cpp/single-number/problem.md: -------------------------------------------------------------------------------- 1 | ## Single Number 2 | 3 | Given a non-empty array of integers `nums`, every element appears twice except for one. Find that single one. 4 | 5 | You must implement a solution with a linear runtime complexity and use only constant extra space. 6 | 7 | #### Constraints: 8 | 9 | - `1 <= nums.length <= 3 * 104` 10 | - `-3 * 104 <= nums[i] <= 3 * 104` 11 | - Each element in the array appears twice except for one element which appears only once. 12 | -------------------------------------------------------------------------------- /Cpp/single-number/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int singleNumber(vector &nums) 6 | { 7 | int result = 0; 8 | for (int num : nums) 9 | result ^= num; // XOR 10 | 11 | return result; 12 | } 13 | 14 | int main() 15 | { 16 | vector nums = {4, 2, 1, 2, 1}; 17 | 18 | int num = singleNumber(nums); 19 | cout << "Number appeared once: " << num << endl; 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /Cpp/spiral_matrix/problem.md: -------------------------------------------------------------------------------- 1 | # Spiral Matrix --- Leetcode 54. 2 | 3 | Given a row x col matrix, print all the elements of the matrix in spiral order. 4 | 5 | Let us consider a 3x3 matrix. 6 | 7 | 1 2 3 8 | 9 | 4 5 6 10 | 11 | 7 8 9 12 | 13 | The spiral print of this matrix will be 14 | 15 | 1->2->3->6->9->8->7->4->5 16 | 17 | ## Sample input 18 | matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 19 | ## Sample output 20 | [1,2,3,6,9,8,7,4,5] -------------------------------------------------------------------------------- /Cpp/sqrt/problem.md: -------------------------------------------------------------------------------- 1 | ## Sqrt(x) 2 | 3 | Given a non-negative integer `x`, return the square root of `x` rounded down to the nearest integer. The returned integer should be non-negative as well. 4 | 5 | You must not use any built-in exponent function or operator. 6 | 7 | For example, do not use `pow(x, 0.5)` in **c++** or `x ** 0.5` in **python**. 8 | 9 | #### Constraints: 10 | 11 | - `0 <= x <= 231 - 1` 12 | -------------------------------------------------------------------------------- /Cpp/sqrt/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int sqrt(int x) 5 | { 6 | if (x == 0 || x == 1) 7 | return x; 8 | 9 | int left = 0; 10 | int right = x; 11 | int result = 0; 12 | 13 | while (left <= right) 14 | { 15 | int mid = (left + right) / 2; 16 | 17 | if (mid <= x / mid) 18 | { 19 | result = mid; 20 | left = mid + 1; 21 | } 22 | else 23 | right = mid - 1; 24 | } 25 | 26 | return result; 27 | } 28 | 29 | int main() 30 | { 31 | int x; 32 | cout << "Enter number: "; 33 | cin >> x; 34 | 35 | int sqrtX = sqrt(x); 36 | cout << "sqrtX: " << sqrtX << endl; 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Cpp/staircase/problem.md: -------------------------------------------------------------------------------- 1 | ## Staircase Detail 2 | 3 | This is a staircase of size _n = 4_: 4 | 5 | ``` 6 | # 7 | ## 8 | ### 9 | #### 10 | ``` 11 | 12 | - Its base and height are both equal to _n_. It is drawn using _#_ symbols and spaces. The last line is not preceded by any spaces. 13 | 14 | - Write a program that prints a staircase of size _n_. 15 | 16 | #### Function Description 17 | 18 | The function has the following parameter(s): 19 | 20 | - **int n**: an integer 21 | 22 | #### Print 23 | 24 | - Print a staircase as described above. 25 | 26 | #### Input Format 27 | 28 | - A single integer, _n_, denoting the size of the staircase. 29 | 30 | #### Constraints 31 | 32 | - 0 <= n <= 100. 33 | 34 | #### Output Format 35 | 36 | - Print a staircase of size _n_ using # symbols and spaces. 37 | 38 | - **Note**: The last line must have _0_ spaces in it. 39 | -------------------------------------------------------------------------------- /Cpp/staircase/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int staircase(int n) 5 | { 6 | int i, j, k; 7 | for (i = 0; i < n; i++) // looping over number of rows 8 | { 9 | for (j = 0; j < n - i - 1; j++) // printing spaces 10 | cout << " "; 11 | 12 | for (k = i; k >= 0; k--) // printing # 13 | cout << "#"; 14 | 15 | cout << endl; 16 | } 17 | } 18 | 19 | int main() 20 | { 21 | int n; 22 | cout << "Input Size: "; 23 | cin >> n; // Taking size of an array. 24 | 25 | staircase(n); 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Cpp/sum_of_list/problem.md: -------------------------------------------------------------------------------- 1 | # Is number k the sum of two number of a given array? 2 | 3 | Given a list of numbers and a number k, return whether any two numbers from the list add up to k. 4 | For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. 5 | -------------------------------------------------------------------------------- /Cpp/the-hurdle-race/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int hurdleRace(vector height, int k) 6 | { 7 | int maxHurdle = 0; 8 | int doses; 9 | for (int i = 0; i < height.size() - 1; i++) 10 | { 11 | maxHurdle = max(height[i], maxHurdle); 12 | doses = maxHurdle - k; 13 | } 14 | 15 | return doses > 0 ? doses : 0; 16 | } 17 | 18 | int main() 19 | { 20 | int size; 21 | cout << "Size of an array: "; 22 | cin >> size; 23 | 24 | vector height(size); 25 | for (int i = 0; i < size; i++) 26 | { 27 | cout << "Enter height of each hurdle: "; 28 | cin >> height[i]; 29 | } 30 | 31 | int k; 32 | cout << "Enter height of the character: "; 33 | cin >> k; 34 | 35 | int result = hurdleRace(height, k); 36 | cout << "Result: " << result << endl; 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /Cpp/time-conversion/problem.md: -------------------------------------------------------------------------------- 1 | ## Time Conversion 2 | 3 | - Given a time in **12-hour AM/PM format**, convert it to military (24-hour) time. 4 | 5 | **Note**: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock. 6 | 7 | - 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock. 8 | 9 | #### Example 10 | 11 | - s = '12:01:00 PM' 12 | Return '12:01:00'. 13 | 14 | - s = '12:01:00 AM' 15 | Return '00:01:00'. 16 | 17 | #### Function Description 18 | 19 | The function should return a new string representing the input time in 24 hour format. 20 | 21 | timeConversion has the following parameter(s): 22 | 23 | - **string s**: a time in 12 hour format 24 | 25 | #### Returns 26 | 27 | - **string**: the time in 12 hour format 28 | 29 | #### Input Format 30 | 31 | - A single string s that represents a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM). 32 | 33 | #### Constraints 34 | 35 | - All input times are valid 36 | -------------------------------------------------------------------------------- /Cpp/triangular_number_sequence/problem.md: -------------------------------------------------------------------------------- 1 | # Triangular Number Sequence 2 | This Triangular Number Sequence is generated from a pattern of dots that form a triangle. The first 5 numbers of the sequence, or dots, are: 3 | 4 | 1, 3, 6, 10, 15 5 | This means that the first triangle has just one dot, the second one has three dots, the third one has 6 dots and so on. 6 | 7 | Write a function that returns the number of dots when given its corresponding triangle number of the sequence. 8 | 9 | Examples 10 | triangle(1) ➞ 1 11 | 12 | triangle(6) ➞ 21 13 | 14 | triangle(215) ➞ 23220 -------------------------------------------------------------------------------- /Cpp/triangular_number_sequence/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int triangular_number_sequence(int number); 4 | 5 | int main() 6 | { 7 | std::cout << triangular_number_sequence(1) << "\n"; 8 | std::cout << triangular_number_sequence(6) << "\n"; 9 | std::cout << triangular_number_sequence(215) << "\n"; 10 | return 0; 11 | } 12 | 13 | int triangular_number_sequence(int number) 14 | { 15 | int ergebnis = 0; 16 | for (int i=1; i <= number; i++) 17 | { 18 | ergebnis +=i; 19 | } 20 | return ergebnis; 21 | } -------------------------------------------------------------------------------- /Cpp/utopian-tree/problem.md: -------------------------------------------------------------------------------- 1 | ## Utopian Tree 2 | 3 | The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter. 4 | 5 | A Utopian Tree sapling with a height of 1 meter is planted at the onset of spring. How tall will the tree be after `n` growth cycles? 6 | 7 | For example, if the number of growth cycles is `n = 5`, the calculations are as follows: 8 | 9 | ``` 10 | Period Height 11 | 0 1 12 | 1 2 13 | 2 3 14 | 3 6 15 | 4 7 16 | 5 14 17 | ``` 18 | 19 | #### Function Description 20 | 21 | utopianTree has the following parameter(s): 22 | 23 | - `int n`: the number of growth cycles to simulate 24 | 25 | #### Returns 26 | 27 | - `int`: the height of the tree after the given number of cycles 28 | 29 | #### Input Format 30 | 31 | - The first line contains an integer, `t`, the number of test cases. 32 | - `t` subsequent lines each contain an integer, `n`, the number of cycles for that test case. 33 | 34 | #### Constraints 35 | 36 | - `1 <= t <= 10` 37 | - `0 <= n <= 60` 38 | -------------------------------------------------------------------------------- /Cpp/utopian-tree/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int utopianTree(int n) 5 | { 6 | int height = 1; 7 | for (int cycle = 1; cycle <= n; cycle++) 8 | { 9 | if (cycle % 2 == 1) 10 | height *= 2; 11 | else 12 | height += 1; 13 | } 14 | 15 | return height; 16 | } 17 | 18 | int main() 19 | { 20 | int size; 21 | cout << "Size: "; 22 | cin >> size; 23 | 24 | for (int i = 0; i < size; i++) 25 | { 26 | int n; 27 | cout << "Enter number: "; 28 | cin >> n; 29 | int result = utopianTree(n); 30 | cout << "Height: " << result << endl; 31 | } 32 | return 0; 33 | } -------------------------------------------------------------------------------- /Cpp/valid-palindrome/problem.md: -------------------------------------------------------------------------------- 1 | ## Valid Palindrome 2 | 3 | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. 4 | 5 | Given a string `s`, return `true` if it is a **_palindrome_**, or `false` otherwise. 6 | 7 | #### Constraints: 8 | 9 | - `1 <= s.length <= 2 * 105` 10 | - `s` consists only of printable ASCII characters. -------------------------------------------------------------------------------- /Cpp/valid-palindrome/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool isPalindrome(string s) 6 | { 7 | transform(s.begin(), s.end(), s.begin(), ::tolower); 8 | 9 | int left = 0; 10 | int right = s.length() - 1; 11 | while (left < right) 12 | { 13 | if (!isalnum(s[left])) 14 | left++; 15 | 16 | else if (!isalnum(s[right])) 17 | right--; 18 | 19 | else 20 | { 21 | if (s[left] != s[right]) 22 | return false; 23 | 24 | left++; 25 | right--; 26 | } 27 | } 28 | return true; 29 | } 30 | 31 | int main() 32 | { 33 | string s = "A man, a plan, a canal: Panama"; 34 | bool isValid = isPalindrome(s); 35 | if (isValid) 36 | { 37 | cout << "The string is valid" << endl; 38 | } 39 | else 40 | { 41 | cout << "The string is not valid" << endl; 42 | } 43 | return 0; 44 | } -------------------------------------------------------------------------------- /Cpp/valid-parenthesis/problem.md: -------------------------------------------------------------------------------- 1 | ## Valid Parenthesis 2 | 3 | Given a string `s` containing just the characters `'(', ')', '{', '}', '['` and `']'`, determine if the input string is valid. 4 | 5 | An input string is valid if: 6 | 7 | - Open brackets must be closed by the same type of brackets. 8 | - Open brackets must be closed in the correct order. 9 | - Every close bracket has a corresponding open bracket of the same type. 10 | 11 | #### Constraints: 12 | 13 | - `1 <= s.length <= 104` 14 | - `s` consists of parentheses only `'()[]{}'`. 15 | -------------------------------------------------------------------------------- /Cpp/valid-sudoku/problem.md: -------------------------------------------------------------------------------- 1 | ## Valid Sudoku 2 | 3 | Determine if a `9 x 9` **Sudoku** board is valid. Only the filled cells need to be validated according to the following rules: 4 | 5 | - Each row must contain the digits `1-9` without repetition. 6 | - Each column must contain the digits `1-9` without repetition. 7 | - Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition. 8 | 9 | **Note**: 10 | 11 | - A Sudoku board (partially filled) could be valid but is not necessarily solvable. 12 | - Only the filled cells need to be validated according to the mentioned rules. 13 | 14 | sudoku-board 15 | -------------------------------------------------------------------------------- /Cpp/validate-binary-search-tree/problem.md: -------------------------------------------------------------------------------- 1 | Given the root of a binary tree, determine if it is a valid binary search tree (BST). 2 | 3 | A valid BST is defined as follows: 4 | 5 | The left subtree of a node contains only nodes with keys less than the node's key. 6 | The right subtree of a node contains only nodes with keys greater than the node's key. 7 | Both the left and right subtrees must also be binary search trees. 8 | 9 | Constraints: 10 | 11 | The number of nodes in the tree is in the range [1, 10^4]. 12 | -2^31 <= Node.val <= 2^31 - 1 13 | -------------------------------------------------------------------------------- /Cpp/validate-binary-search-tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isBST(TreeNode* root, long min, long max){ 15 | 16 | if(root == NULL) return true; 17 | 18 | if(root->valval>min && isBST(root->left, min, root->val) && isBST(root->right, root->val, max)) 19 | return true; 20 | 21 | else return false; 22 | } 23 | bool isValidBST(TreeNode* root) { 24 | if(root->left == NULL && root->right == NULL) return true; 25 | 26 | return isBST(root, -2147483649, 2147483648); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Cpp/very-big-sum/problem.md: -------------------------------------------------------------------------------- 1 | ## aVeryBigSum 2 | 3 | In this challenge, you are required to calculate and print the sum of the elements in an array, keeping in mind that some of those integers may be quite large. 4 | 5 | **aVeryBigSum** has the following parameter(s): 6 | 7 | - int ar[n]: an array of integers. 8 | 9 | ### Return 10 | 11 | - long: the sum of all array elements. 12 | 13 | ### Input Format 14 | 15 | - The first line of the input consists of an integer. 16 | - The next line contains space-separated integers contained in the array. 17 | 18 | ### Output Format 19 | 20 | - Return the integer sum of the elements in the array. 21 | 22 | ### Constraints 23 | 24 | - 1 <= n <= 10 25 | - 0 <= ar[i] <= 10^10 26 | -------------------------------------------------------------------------------- /Cpp/very-big-sum/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int aVeryBigSum(int ar[], int n) 5 | { 6 | long sum = 0; 7 | for (int i = 0; i < n; i++) 8 | sum += ar[i]; 9 | 10 | return sum; 11 | } 12 | 13 | int main() 14 | { 15 | int n; 16 | cout << "Size: "; 17 | cin >> n; // Take total number of inputs 18 | 19 | int ar[n]; 20 | for (int i = 0; i < n; i++) 21 | { 22 | cout << "Input Value: "; 23 | cin >> ar[i]; 24 | } 25 | 26 | long result = aVeryBigSum(ar, n); 27 | cout << "Result: " << result << endl; 28 | return 0; 29 | } -------------------------------------------------------------------------------- /Cpp/viral-advertising/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int viralAdvertising(int n) 6 | { 7 | int shared = 5, likes = 0, cumulative = 0; 8 | 9 | for (int days = 1; days <= n; days++) 10 | { 11 | likes = floor(shared / 2); 12 | cumulative += likes; 13 | shared = likes * 3; 14 | } 15 | 16 | return cumulative; 17 | } 18 | 19 | int main() 20 | { 21 | int n; 22 | cout << "Number of days: "; 23 | cin >> n; 24 | 25 | int result = viralAdvertising(n); 26 | cout << "Result: " << result << endl; 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /Java/Arrangingcoin/problem.md: -------------------------------------------------------------------------------- 1 | You have n coins and you want to build a staircase with these coins. 2 | The staircase consists of k rows where the ith row has exactly i coins. 3 | The last row of the staircase may be incomplete. 4 | 5 | Given the integer n, return the number of complete rows of the staircase you will build. 6 | 7 | Example 1: 8 | 9 | Input: n = 5 10 | Output: 2 11 | Explanation: Because the 3rd row is incomplete, we return 2. 12 | 13 | Example 2: 14 | 15 | Input: n = 8 16 | Output: 3 17 | Explanation: Because the 4th row is incomplete, we return 3. 18 | 19 | problem: [link](https://leetcode.com/problems/arranging-coins/) -------------------------------------------------------------------------------- /Java/Count of Smaller Numbers After Self/problem.md: -------------------------------------------------------------------------------- 1 | ## Problem Statement 2 | Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i]. 3 | 4 | ## Example 1: 5 | 6 | Input: nums = [5,2,6,1] 7 | Output: [2,1,1,0] 8 | Explanation: 9 | To the right of 5 there are 2 smaller elements (2 and 1). 10 | To the right of 2 there is only 1 smaller element (1). 11 | To the right of 6 there is 1 smaller element (1). 12 | To the right of 1 there is 0 smaller element. 13 | 14 | ## Example 2: 15 | 16 | Input: nums = [-1] 17 | Output: [0] 18 | 19 | ## Example 3: 20 | 21 | Input: nums = [-1,-1] 22 | Output: [0,0] 23 | 24 | ## Constraints: 25 | 26 | 1 <= nums.length <= 105 27 | -104 <= nums[i] <= 104 28 | 29 | PROBLEM STATEMENT NUMBER: 315 -------------------------------------------------------------------------------- /Java/Find the kth Bit in the nth Binary String/problem.md: -------------------------------------------------------------------------------- 1 | Given two positive integers **n** and **k**, the binary string **Sn** is formed as follows: 2 | 3 | - **S1** = `"0"` 4 | - **Si** = **Si-1** + `"1"` + `reverse(invert(Si-1))` for **i > 1** 5 | 6 | Where: 7 | - `+` denotes the **concatenation** operation 8 | - `reverse(x)` returns the **reversed** string **x** 9 | - `invert(x)` **inverts** all the bits in **x** (0 changes to 1 and 1 changes to 0) 10 | 11 | ## Example 12 | 13 | The first four strings in the sequence are: 14 | 15 | - **S1** = `"0"` 16 | - **S2** = `"011"` 17 | - **S3** = `"0111001"` 18 | - **S4** = `"011100110110001"` 19 | 20 | ## Problem Statement 21 | 22 | Return the **kth** bit in **Sn**. 23 | 24 | It is guaranteed that **k** is valid for the given **n**. 25 | -------------------------------------------------------------------------------- /Java/Group Anagrams/problem.md: -------------------------------------------------------------------------------- 1 | Given an array of strings strs, group the anagrams together. You can return the answer in any order. 2 | 3 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 10 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 11 | Example 2: 12 | 13 | Input: strs = [""] 14 | Output: [[""]] 15 | Example 3: 16 | 17 | Input: strs = ["a"] 18 | Output: [["a"]] 19 | 20 | 21 | Constraints: 22 | 23 | 1 <= strs.length <= 104 24 | 0 <= strs[i].length <= 100 25 | strs[i] consists of lowercase English letters. 26 | 27 | problem link: https://leetcode.com/problems/group-anagrams/description/ -------------------------------------------------------------------------------- /Java/Horses/problem.md: -------------------------------------------------------------------------------- 1 | - **Name** - Racing Horses 2 | - **Problem Code** - HORSES 3 | - **Level** - Beginner 4 | - **Source** - [Link](https://www.codechef.com/practice/PJASOR01/problems/HORSES) -------------------------------------------------------------------------------- /Java/Longest Happy String/problem.md: -------------------------------------------------------------------------------- 1 | 2 | A string `s` is called **happy** if it satisfies the following conditions: 3 | 4 | 1. `s` only contains the letters **'a'**, **'b'**, and **'c'**. 5 | 2. `s` does not contain any of the following as a substring: 6 | - `"aaa"` 7 | - `"bbb"` 8 | - `"ccc"` 9 | 3. `s` contains at most **a** occurrences of the letter `'a'`. 10 | 4. `s` contains at most **b** occurrences of the letter `'b'`. 11 | 5. `s` contains at most **c** occurrences of the letter `'c'`. 12 | 13 | ## Problem Statement 14 | 15 | Given three integers **a**, **b**, and **c**, return the longest possible happy string. 16 | 17 | - If there are multiple longest happy strings, return any of them. 18 | - If there is no such string, return the empty string `""`. 19 | 20 | ## Note 21 | 22 | A **substring** is a contiguous sequence of characters within a string. -------------------------------------------------------------------------------- /Java/Longest Square Streak in Array/problem.md: -------------------------------------------------------------------------------- 1 | ## Problem Description 2 | 3 | You are given an integer array `nums`. Your task is to find the longest **square streak** in a subsequence of the array. 4 | 5 | ### Definition of a Square Streak 6 | 7 | A subsequence of `nums` is called a **square streak** if: 8 | 9 | - The length of the subsequence is at least 2, and 10 | - After sorting the subsequence, each element (except the first) is the square of the previous element. 11 | 12 | ### Return Value 13 | 14 | You need to return: 15 | - The length of the longest square streak in the array, or 16 | - `-1` if there is no square streak. 17 | 18 | ### Definition of a Subsequence 19 | 20 | A subsequence is an array that can be derived from another array by deleting some or no elements, without changing the order of the remaining elements. 21 | 22 | ## Example 23 | 24 | Given the input: 25 | 26 | ```plaintext 27 | nums = [2, 3, 5, 4, 9, 25, 16] -------------------------------------------------------------------------------- /Java/Longest_common_prefix/problem.md: -------------------------------------------------------------------------------- 1 | Write a function to find the longest common prefix string amongst an array of strings. 2 | 3 | If there is no common prefix, return an empty string "". 4 | 5 | problem :- [Link](https://leetcode.com/problems/longest-common-prefix/) 6 | 7 | Example 1: 8 | Input: strs = ["flower","flow","flight"] 9 | Output: "fl" 10 | 11 | Example 2: 12 | Input: strs = ["dog","racecar","car"] 13 | Output: "" 14 | Explanation: There is no common prefix among the input strings. 15 | 16 | 17 | Constraints: 18 | 1 <= strs.length <= 200 19 | 0 <= strs[i].length <= 200 20 | strs[i] consists of only lowercase English letters. -------------------------------------------------------------------------------- /Java/Minimum Add to Make Parenthesis Valid/solution.java: -------------------------------------------------------------------------------- 1 | // Problem URL:- https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ 2 | 3 | import java.util.*; 4 | public class solution { 5 | static Scanner obj=new Scanner(System.in); 6 | 7 | public static void main(String args[]){ 8 | run(); 9 | } 10 | 11 | private static void run(){ 12 | String str=obj.nextLine(); 13 | int ans=minAddToMakeValid(str); 14 | System.out.println(ans); 15 | } 16 | 17 | public static int minAddToMakeValid(String s) { 18 | int opening=0, closing=0; 19 | 20 | for(int i=0;i0) 29 | { 30 | opening--; 31 | } 32 | else 33 | closing++; 34 | } 35 | } 36 | return opening +closing; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Java/Minimum Number of Swaps to make the String Balanced/problem.md: -------------------------------------------------------------------------------- 1 | You are given a 0-indexed string **s** of even length **n**. The string consists of exactly **n / 2** opening brackets `'['` and **n / 2** closing brackets `']'`. 2 | 3 | A string is called **balanced** if and only if: 4 | - It is the empty string, or 5 | - It can be written as **AB**, where both **A** and **B** are balanced strings, or 6 | - It can be written as **[C]**, where **C** is a balanced string. 7 | 8 | You may swap the brackets at any two indices any number of times. 9 | 10 | Return the **minimum number of swaps** to make **s** balanced. -------------------------------------------------------------------------------- /Java/Remove Subfolders from File System/problem.md: -------------------------------------------------------------------------------- 1 | 2 | ## Problem Description 3 | 4 | Given a list of folder paths, return the list of folders after removing all sub-folders contained within other folders. You can return the result in any order. 5 | 6 | ### Definition of Sub-folder 7 | A folder `i` is considered a sub-folder of another folder `j` if it is located within `j`. Specifically, for `folder[i]` to be a sub-folder of `folder[j]`, it must start with `folder[j]`, followed by a `"/"`. 8 | 9 | For example: 10 | - `"/a/b"` is a sub-folder of `"/a"`, but 11 | - `"/b"` is **not** a sub-folder of `"/a/b/c"`. 12 | 13 | ### Path Format 14 | 15 | - A valid path consists of one or more concatenated strings of the form: `'/'` followed by one or more lowercase English letters. 16 | 17 | Examples of valid paths: 18 | - `"/leetcode"` 19 | - `"/leetcode/problems"` 20 | 21 | Examples of invalid paths: 22 | - An empty string `""` 23 | - A path consisting of only a `'/'` 24 | 25 | ## Example 26 | 27 | Given the input: 28 | 29 | ```plaintext 30 | ["/a", "/a/b", "/c/d", "/c/d/e", "/c/f"] -------------------------------------------------------------------------------- /Java/Separate Black and White Balls/problem.md: -------------------------------------------------------------------------------- 1 | There are **n** balls on a table, and each ball has a color: **black** or **white**. 2 | 3 | You are given a **0-indexed binary string** `s` of length **n**, where: 4 | 5 | - `1` represents a **black** ball 6 | - `0` represents a **white** ball 7 | 8 | ## Objective 9 | 10 | In each step, you can choose two adjacent balls and swap them. 11 | 12 | ## Problem Statement 13 | 14 | Return the minimum number of steps required to: 15 | 16 | - Group all the **black** balls to the right 17 | - Group all the **white** balls to the left 18 | -------------------------------------------------------------------------------- /Java/String to integer/problem.md: -------------------------------------------------------------------------------- 1 | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). 2 | 3 | The algorithm for myAtoi(string s) is as follows: 4 | 5 | Read in and ignore any leading whitespace. 6 | Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. 7 | Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. 8 | Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2). 9 | If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1. 10 | Return the integer as the final result. 11 | -------------------------------------------------------------------------------- /Java/fmPositive/problem.md: -------------------------------------------------------------------------------- 1 | Given an unsorted integer array nums, return the smallest missing positive integer. 2 | You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. 3 | 4 | Example 1: 5 | 6 | Input: nums = [1,2,0] 7 | Output: 3 8 | Explanation: The numbers in the range [1,2] are all in the array. 9 | Example 2: 10 | 11 | Input: nums = [3,4,-1,1] 12 | Output: 2 13 | Explanation: 1 is in the array but 2 is missing. 14 | Example 3: 15 | 16 | Input: nums = [7,8,9,11,12] 17 | Output: 1 18 | Explanation: The smallest positive integer 1 is missing. 19 | 20 | -------------------------------------------------------------------------------- /Js/20-valid-parentheses/problem.md: -------------------------------------------------------------------------------- 1 | # Valid Parentheses 2 | 3 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 4 | 5 | An input string is valid if: 6 | 7 | Open brackets must be closed by the same type of brackets. 8 | Open brackets must be closed in the correct order. 9 | Every close bracket has a corresponding open bracket of the same type. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: `s = "()"` 16 | Output: `true` 17 | 18 | Example 2: 19 | 20 | Input: `s = "()[]{}"` 21 | Output: `true` 22 | 23 | Example 3: 24 | 25 | Input: `s = "(]"` 26 | Output: `false` 27 | 28 | 29 | 30 | Constraints: 31 | 1 <= s.length <= 104 32 | s consists of parentheses only '()[]{}'. 33 | 34 | -------------------------------------------------------------------------------- /Js/2605-Counter/problem.md: -------------------------------------------------------------------------------- 1 | Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc). 2 | 3 | Example 1: 4 | 5 | Input: 6 | n = 10 7 | ["call","call","call"] 8 | Output: [10,11,12] 9 | Explanation: 10 | counter() = 10 // The first time counter() is called, it returns n. 11 | counter() = 11 // Returns 1 more than the previous time. 12 | counter() = 12 // Returns 1 more than the previous time. 13 | Example 2: 14 | 15 | Input: 16 | n = -2 17 | ["call","call","call","call","call"] 18 | Output: [-2,-1,0,1,2] 19 | Explanation: counter() initially returns -2. Then increases after each sebsequent call. 20 | 21 | Constraints: 22 | 23 | -1000 <= n <= 1000 24 | 0 <= calls.length <= 1000 25 | calls[i] === "call" 26 | -------------------------------------------------------------------------------- /Js/2605-Counter/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @return {Function} counter 4 | */ 5 | let createCounter = function (n) { 6 | let count = n; 7 | 8 | /** 9 | * This function increments and returns the counter value. 10 | * @returns {number} The current value of the counter. 11 | */ 12 | 13 | const counter = () => { 14 | return count++; 15 | }; 16 | 17 | return counter; 18 | }; 19 | 20 | const counter = createCounter(10); 21 | counter(); 22 | counter(); 23 | counter(); 24 | -------------------------------------------------------------------------------- /Js/Join_2_arrays_by_Id/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Array} arr1 3 | * @param {Array} arr2 4 | * @return {Array} 5 | */ 6 | var join = function (arr1, arr2) { 7 | // Combine both arrays 8 | var joinedArray = arr1.concat(arr2); 9 | 10 | // Create an object to store unique objects based on id 11 | var uniqueObjects = {}; 12 | 13 | // Iterate through the joined array 14 | for (var i = 0; i < joinedArray.length; i++) { 15 | var obj = joinedArray[i]; 16 | var id = obj.id; 17 | 18 | // If this id already exists in the unique objects, merge the properties 19 | if (uniqueObjects[id]) { 20 | uniqueObjects[id] = Object.assign(uniqueObjects[id], obj); 21 | } else { 22 | // If it's a new id, simply add it to the unique objects 23 | uniqueObjects[id] = obj; 24 | } 25 | } 26 | 27 | // Convert the unique objects back to an array 28 | var resultArray = Object.values(uniqueObjects); 29 | 30 | // Sort the result array by id in ascending order 31 | resultArray.sort(function (a, b) { 32 | return a.id - b.id; 33 | }); 34 | 35 | return resultArray; 36 | }; 37 | -------------------------------------------------------------------------------- /Py/0002.Add_Two_numbers/problem.md: -------------------------------------------------------------------------------- 1 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. 2 | 3 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | 10 | Input: l1 = [2,4,3], l2 = [5,6,4] 11 | Output: [7,0,8] 12 | Explanation: 342 + 465 = 807. 13 | Example 2: 14 | 15 | Input: l1 = [0], l2 = [0] 16 | Output: [0] 17 | Example 3: 18 | 19 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] 20 | Output: [8,9,9,9,0,0,0,1] 21 | 22 | 23 | Constraints: 24 | 25 | The number of nodes in each linked list is in the range [1, 100]. 26 | 0 <= Node.val <= 9 27 | It is guaranteed that the list represents a number that does not have leading zeros. -------------------------------------------------------------------------------- /Py/0002.Add_Two_numbers/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | 4 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 5 | carry = 0 6 | head = curr = ListNode() 7 | 8 | while l1 and l2: 9 | total = l1.val + l2.val + carry 10 | curr.next = ListNode(total% 10) 11 | carry = total // 10 12 | l1,l2,curr = l1.next, l2.next,curr.next 13 | 14 | while l1: 15 | total = l1.val + carry 16 | curr.next = ListNode(total%10) 17 | carry = total // 10 18 | l1, curr = l1.next, curr.next 19 | 20 | while l2: 21 | total = l2.val + carry 22 | curr.next = ListNode(total%10) 23 | carry = total//10 24 | l2, curr = l2.next, curr.next 25 | if carry > 0: 26 | curr.next = ListNode(carry) 27 | 28 | return head.next 29 | 30 | -------------------------------------------------------------------------------- /Py/0004. Median of Two Sorted Arrays/problem.md: -------------------------------------------------------------------------------- 1 | Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. 2 | 3 | The overall run time complexity should be O(log (m+n)). 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: nums1 = [1,3], nums2 = [2] 10 | Output: 2.00000 11 | Explanation: merged array = [1,2,3] and median is 2. 12 | Example 2: 13 | 14 | Input: nums1 = [1,2], nums2 = [3,4] 15 | Output: 2.50000 16 | Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. 17 | 18 | 19 | Constraints: 20 | 21 | nums1.length == m 22 | nums2.length == n 23 | 0 <= m <= 1000 24 | 0 <= n <= 1000 25 | 1 <= m + n <= 2000 26 | -106 <= nums1[i], nums2[i] <= 106 -------------------------------------------------------------------------------- /Py/0007.Reverse_Integer/problem.md: -------------------------------------------------------------------------------- 1 | Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. 2 | 3 | Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: x = 123 10 | Output: 321 11 | Example 2: 12 | 13 | Input: x = -123 14 | Output: -321 15 | Example 3: 16 | 17 | Input: x = 120 18 | Output: 21 19 | 20 | 21 | Constraints: 22 | 23 | -231 <= x <= 231 - 1 -------------------------------------------------------------------------------- /Py/0007.Reverse_Integer/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | if x > (2**31 -1): 4 | return 0 5 | if x < (-2**31): 6 | return 0 7 | if x >= 0: 8 | if int(str(x)[::-1]) <= (2**31 - 1): 9 | return int(str(x)[::-1]) 10 | return 0 11 | else: 12 | if -int(str(x)[-1:0:-1]) >= (-2**31): 13 | return -int(str(x)[-1:0:-1]) 14 | return 0 -------------------------------------------------------------------------------- /Py/0013-Roman_to_Integer/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | d={"I":1, "IV":4, "V":5, "IX":9, "X":10, "XL":40, "L":50, "XC":90, "C":100, "CD":400, "D":500, "CM":900, "M":1000} 4 | a=0 5 | i=0 6 | while i<=len(s)-1: 7 | if (i+1<=len(s)-1) and ((s[i]+s[i+1]) in d.keys()): 8 | a=a+d.get(s[i]+s[i+1]) 9 | i+=2 10 | 11 | else: 12 | a=a+d.get(s[i]) 13 | i+=1 14 | #a=a+d.get(s[-1]) 15 | return a -------------------------------------------------------------------------------- /Py/0014-longest-common-prefix/problem.md: -------------------------------------------------------------------------------- 1 |

14. Longest Common Prefix

2 | 3 | 4 |

Easy

5 | 6 |
7 | 8 |

Write a function to find the longest common prefix string amongst an array of strings.

9 | 10 |

If there is no common prefix, return an empty string "".

11 | 12 |

 

13 |

Example 1:

14 | 15 |
Input: strs = ["flower","flow","flight"]
16 | Output: "fl"
17 | 
18 | 19 |

Example 2:

20 | 21 |
Input: strs = ["dog","racecar","car"]
22 | Output: ""
23 | Explanation: There is no common prefix among the input strings.
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 |
    30 |
  • 1 <= strs.length <= 200
  • 31 |
  • 0 <= strs[i].length <= 200
  • 32 |
  • strs[i] consists of only lowercase English letters.
  • 33 |
34 |
35 | -------------------------------------------------------------------------------- /Py/0014-longest-common-prefix/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs: List[str]) -> str: 3 | # Sort the list of strings 4 | strs.sort() 5 | 6 | # Initialize the answer string and get the first and last strings 7 | ans = "" 8 | fst, lst = strs[0], strs[-1] 9 | 10 | # loop through the characters of the first and last strings 11 | for i in range(min(len(fst), len(lst))): 12 | # If the characters at the current position are the same, add to the answer string 13 | if fst[i] == lst[i]: 14 | ans += fst[i] 15 | # If not, break out of the loop as this is where the common prefix ends 16 | else: 17 | break 18 | 19 | # Return the computed common prefix 20 | return ans -------------------------------------------------------------------------------- /Py/0015-3sum/problem.md: -------------------------------------------------------------------------------- 1 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 2 | 3 | Notice that the solution set must not contain duplicate triplets. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: nums = [-1,0,1,2,-1,-4] 10 | Output: [[-1,-1,2],[-1,0,1]] 11 | Explanation: 12 | nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. 13 | nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. 14 | nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. 15 | The distinct triplets are [-1,0,1] and [-1,-1,2]. 16 | Notice that the order of the output and the order of the triplets does not matter. 17 | Example 2: 18 | 19 | Input: nums = [0,1,1] 20 | Output: [] 21 | Explanation: The only possible triplet does not sum up to 0. 22 | Example 3: 23 | 24 | Input: nums = [0,0,0] 25 | Output: [[0,0,0]] 26 | Explanation: The only possible triplet sums up to 0. 27 | 28 | 29 | Constraints: 30 | 31 | 3 <= nums.length <= 3000 32 | -105 <= nums[i] <= 105 -------------------------------------------------------------------------------- /Py/0015-3sum/solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def threeSum(self, nums): 3 | if len(nums) < 3: 4 | return [] 5 | nums.sort() 6 | res = [] 7 | for i, x in enumerate(nums[:-2]): 8 | if i >= 1 and x == nums[i-1]: 9 | continue 10 | l, r = i+1, len(nums)-1 11 | while l < r: 12 | s = nums[i] + nums[l] + nums[r] 13 | if s < 0: 14 | l += 1 15 | elif s > 0: 16 | r -= 1 17 | else: 18 | res.append((nums[i], nums[l], nums[r])) 19 | while l < r and nums[l] == nums[l+1]: 20 | l += 1 21 | while l < r and nums[r] == nums[r-1]: 22 | r -= 1 23 | l += 1 24 | r -= 1 25 | return res -------------------------------------------------------------------------------- /Py/0016-3Sum-Closest/problem.md: -------------------------------------------------------------------------------- 1 | Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. 2 | 3 | Return the sum of the three integers. 4 | 5 | You may assume that each input would have exactly one solution. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: nums = [-1,2,1,-4], target = 1 12 | Output: 2 13 | Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 14 | Example 2: 15 | 16 | Input: nums = [0,0,0], target = 1 17 | Output: 0 18 | Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). 19 | 20 | 21 | Constraints: 22 | 23 | 3 <= nums.length <= 500 24 | -1000 <= nums[i] <= 1000 25 | -104 <= target <= 104 -------------------------------------------------------------------------------- /Py/0017-Letter-Combinations-of-a-Phone-Number/problem.md: -------------------------------------------------------------------------------- 1 | Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. 2 | 3 | A mapping of digits to letters (just like on the telephone buttons) is given [here](https://assets.leetcode.com/uploads/2022/03/15/1200px-telephone-keypad2svg.png). Note that 1 does not map to any letters. 4 | 5 | 6 | Example 1: 7 | 8 | Input: digits = "23" 9 | Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] 10 | Example 2: 11 | 12 | Input: digits = "" 13 | Output: [] 14 | Example 3: 15 | 16 | Input: digits = "2" 17 | Output: ["a","b","c"] 18 | 19 | 20 | Constraints: 21 | 22 | 0 <= digits.length <= 4 23 | digits[i] is a digit in the range ['2', '9']. -------------------------------------------------------------------------------- /Py/0017-Letter-Combinations-of-a-Phone-Number/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCombinations(self, digits: str) -> List[str]: 3 | if not digits: 4 | return [] 5 | 6 | digit_to_letters = { 7 | '2': 'abc', 8 | '3': 'def', 9 | '4': 'ghi', 10 | '5': 'jkl', 11 | '6': 'mno', 12 | '7': 'pqrs', 13 | '8': 'tuv', 14 | '9': 'wxyz' 15 | } 16 | 17 | queue = [''] 18 | 19 | for digit in digits: 20 | letters = digit_to_letters[digit] 21 | new_queue = [] 22 | 23 | for combination in queue: 24 | for letter in letters: 25 | new_queue.append(combination + letter) 26 | 27 | queue = new_queue 28 | 29 | return queue -------------------------------------------------------------------------------- /Py/0018-4Sum/problem.md: -------------------------------------------------------------------------------- 1 | Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 2 | 3 | 0 <= a, b, c, d < n 4 | a, b, c, and d are distinct. 5 | nums[a] + nums[b] + nums[c] + nums[d] == target 6 | You may return the answer in any order. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [1,0,-1,0,-2,2], target = 0 13 | Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] 14 | Example 2: 15 | 16 | Input: nums = [2,2,2,2,2], target = 8 17 | Output: [[2,2,2,2]] 18 | 19 | 20 | Constraints: 21 | 22 | 1 <= nums.length <= 200 23 | -109 <= nums[i] <= 109 24 | -109 <= target <= 109 -------------------------------------------------------------------------------- /Py/0022-generate-parenthesis/problem.md: -------------------------------------------------------------------------------- 1 |

22. Generate Parentheses

2 | 3 |

Medium

4 | 5 |
6 |

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

7 | 8 |

 

9 |

Example 1:

10 |
Input: n = 3
11 | Output: ["((()))","(()())","(())()","()(())","()()()"]
12 | 

Example 2:

13 |
Input: n = 1
14 | Output: ["()"]
15 | 
16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • 1 <= n <= 8
  • 21 |
22 |
23 | -------------------------------------------------------------------------------- /Py/0022-generate-parenthesis/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateParenthesis(self, n): 3 | # Helper function for generating valid parentheses combinations 4 | def parenthesis_helper(open, close, s): 5 | # If the string has reached the desired length (2 * n), add it to the result list 6 | if len(s) == 2 * n: 7 | result.append(s) 8 | return 9 | # If we can still add open parentheses, recursively call with an added open parenthesis 10 | if open < n: 11 | parenthesis_helper(open + 1, close, s + '(') 12 | # If we can add a closing parenthesis without violating the balance, recursively call with a close parenthesis 13 | if close < open: 14 | parenthesis_helper(open, close + 1, s + ')') 15 | 16 | result = [] # Initialize the result list to store valid combinations 17 | parenthesis_helper(0, 0, "") # Start the recursive process with no open or close parentheses 18 | return result # Return the list of valid combinations 19 | -------------------------------------------------------------------------------- /Py/0026 Remove Duplicate from Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | def binary_search(nums, low, high, val): 2 | n = len(nums) 3 | res = -1 4 | while low <= high: 5 | mid = low + (high - low) // 2 6 | if nums[mid] <= val: 7 | low = mid + 1 8 | else: 9 | res = mid 10 | high = mid - 1 11 | if res == -1: 12 | return n 13 | return res 14 | 15 | def remove_duplicates(nums): 16 | n = len(nums) 17 | idx = 0 18 | 19 | while idx != n: 20 | i = binary_search(nums, idx + 1, n - 1, nums[idx]) 21 | 22 | if i == n: 23 | return idx + 1 24 | idx += 1 25 | nums[idx] = nums[i] 26 | 27 | return idx + 1 28 | 29 | # Driver code 30 | if __name__ == "__main__": 31 | arr = [1, 2, 2, 3, 4, 4, 4, 5, 5] 32 | n = remove_duplicates(arr) 33 | for i in range(n): 34 | print(arr[i], end=" ") -------------------------------------------------------------------------------- /Py/0042-trapping-rain-water/problem.md: -------------------------------------------------------------------------------- 1 | # Problem: Trapping Rain Water 2 | 3 | ## Category: Hard 4 | 5 | 6 | ## Description 7 | Given `n` non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. 8 | 9 | ## Example 1 10 | 11 | 12 | 13 | ### Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] 14 | ### Output: 6 15 | ### Explanation: 16 | The above elevation map (black section) is represented by array `[0,1,0,2,1,0,1,3,2,1,2,1]`. In this case, 6 units of rainwater (blue section) are being trapped. 17 | 18 | ## Example 2 19 | ### Input: height = [4,2,0,3,2,5] 20 | ### Output: 9 21 | 22 | 23 | ## Constraints 24 | - `n == height.length` 25 | - `1 <= n <= 2 * 10^4` 26 | - `0 <= height[i] <= 10^5` 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Py/0050-pow(x n)/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | # Initialize the result variable to 1 4 | ans = 1 5 | 6 | # Convert n to a long long to handle the edge case when n is INT_MIN 7 | m = n 8 | 9 | # If n is negative, make it positive and keep track of it 10 | if n < 0: 11 | m = (-1) * m 12 | 13 | # Main loop for exponentiation 14 | while m > 0: 15 | # If m is odd, multiply the result by x and decrement m by 1 16 | if m % 2 == 1: 17 | ans = ans * x 18 | m -= 1 19 | # If m is even, square x and divide m by 2 20 | else: 21 | x = x * x 22 | m = m // 2 23 | 24 | # If n was originally negative, return the reciprocal of ans, otherwise, return ans 25 | return 1 / ans if n < 0 else ans 26 | -------------------------------------------------------------------------------- /Py/0061-rotate-list/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: 3 | if head is None or head.next is None or k == 0: 4 | return head 5 | 6 | length = 1 7 | current = head 8 | 9 | # Calculate the length of the linked list 10 | while current.next: 11 | length += 1 12 | current = current.next 13 | 14 | # Connect the last node to the head to make it a circular linked list 15 | current.next = head 16 | 17 | # Calculate the actual number of rotations needed (k % length) 18 | k = k % length 19 | 20 | # Calculate the new position of the last node after rotation 21 | k = length - k 22 | 23 | # Move the current pointer to the new position of the last node 24 | for _ in range(k): 25 | current = current.next 26 | 27 | # Update the head and break the circular structure 28 | new_head = current.next 29 | current.next = None 30 | 31 | # return the new head of the linked list 32 | return new_head -------------------------------------------------------------------------------- /Py/0078-subsets/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsets(self, nums: List[int]) -> List[List[int]]: 3 | def subsetHelper(i: int, nums: List[int], output: List[int], res: List[List[int]]) -> None: 4 | # Base case: if we've considered all numbers 5 | if i == len(nums): 6 | # Add the current subset to the result 7 | res.append(output.copy()) 8 | return 9 | 10 | # Include the current number in the subset 11 | output.append(nums[i]) 12 | subsetHelper(i+1, nums, output, res) 13 | 14 | # Exclude the current number from the subset (undo previous step) 15 | output.pop() 16 | subsetHelper(i+1, nums, output, res) 17 | 18 | # Initialize the result list to store all subsets 19 | res = [] 20 | # Start the recursive function from the first number 21 | subsetHelper(0, nums, [], res) 22 | return res -------------------------------------------------------------------------------- /Py/0128-longest-consecutive-sequence/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestConsecutive(self, nums: List[int]) -> int: 3 | # Sort the input list in ascending order 4 | nums.sort() 5 | 6 | # Initialize variables 7 | longest = 0 8 | current_streak = 0 9 | 10 | # Iterate through the sorted list to find consecutive subsequences 11 | for i in range(len(nums)): 12 | if i == 0: 13 | current_streak = 1 14 | elif nums[i] == nums[i - 1]: 15 | # Skip duplicate elements 16 | continue 17 | elif nums[i] == nums[i - 1] + 1: 18 | # If the current number is consecutive to the previous one 19 | current_streak += 1 20 | else: 21 | # If not consecutive, update the longest streak if necessary 22 | longest = max(longest, current_streak) 23 | current_streak = 1 24 | 25 | # Return the maximum of the longest streak and the current streak 26 | return max(longest, current_streak) 27 | -------------------------------------------------------------------------------- /Py/0204-Count-Primes/problem.md: -------------------------------------------------------------------------------- 1 | **Leetcode - 204 : Count Primes** 2 | 3 | Given an integer n, return the number of prime numbers that are strictly less than n. 4 | 5 | Example 1: 6 | 7 | Input: n = 10 8 | Output: 4 9 | Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 10 | Example 2: 11 | 12 | Input: n = 0 13 | Output: 0 14 | Example 3: 15 | 16 | Input: n = 1 17 | Output: 0 18 | 19 | Constraints: 20 | 21 | 0 <= n <= 5 * 106 22 | 23 | Algorithm used: Sieve of Eratosthenes -------------------------------------------------------------------------------- /Py/0204-Count-Primes/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPrimes(self, n: int) -> int: 3 | # no primes lesser than 2 4 | if n<2: 5 | return 0 6 | # initialise a list with n True's, assume all numbers >=2 are prime 7 | primes = [True]*n 8 | ans = 0 9 | for i in range(2,n): 10 | # if prime then increment count 11 | if primes[i]: 12 | ans+=1 13 | '''mark all multiples of i (starting from i*i) as non-prime 14 | start at i*i because smaller multiples of i (like i*2, i*3, ...) 15 | will have already been marked by previous primes''' 16 | for j in range(i*i,n,i): 17 | primes[j] = False 18 | 19 | return ans 20 | 21 | if __name__ == "__main__": 22 | soln = Solution() 23 | # Test cases 24 | print(soln.countPrimes(10)) 25 | print(soln.countPrimes(0)) 26 | print(soln.countPrimes(1)) 27 | print(soln.countPrimes(20)) 28 | print(soln.countPrimes(30)) 29 | 30 | # Time complexity: O(nloglogn) 31 | # Space complexity: O(n) 32 | -------------------------------------------------------------------------------- /Py/0273-Integer-to-English-Words/problem.md: -------------------------------------------------------------------------------- 1 | # Integer to English Words 2 | 3 | ## Problem Description 4 | Convert a non-negative integer `num` to its English words representation. 5 | 6 | ## Objective 7 | Given an integer `num`, return its representation in English words. 8 | 9 | --- 10 | 11 | ### Constraints 12 | - `0 <= num <= 2^31 - 1` 13 | 14 | ### Examples 15 | 16 | **Example 1** 17 | 18 | **Input** 19 | ```plaintext 20 | num = 123 21 | ``` 22 | 23 | **Output** 24 | ```plaintext 25 | "One Hundred Twenty Three" 26 | ``` 27 | 28 | **Example 2** 29 | 30 | **Input** 31 | ```plaintext 32 | num = 12345 33 | ``` 34 | 35 | **Output** 36 | ```plaintext 37 | "Twelve Thousand Three Hundred Forty Five" 38 | ``` -------------------------------------------------------------------------------- /Py/0342.Power_of_Four/problem.md: -------------------------------------------------------------------------------- 1 | Given an integer n, return true if it is a power of four. Otherwise, return false. 2 | 3 | An integer n is a power of four, if there exists an integer x such that n == 4x. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: n = 16 10 | Output: true 11 | Example 2: 12 | 13 | Input: n = 5 14 | Output: false 15 | Example 3: 16 | 17 | Input: n = 1 18 | Output: true 19 | 20 | 21 | Constraints: 22 | 23 | -231 <= n <= 231 - 1 -------------------------------------------------------------------------------- /Py/0342.Power_of_Four/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfFour(self, n: int) -> bool: 3 | a=0 4 | ans=False 5 | while 4**a<=n: 6 | if 4**a==n: 7 | ans=True 8 | break 9 | 10 | else : 11 | a+=1 12 | return ans -------------------------------------------------------------------------------- /Py/0404-sum-of-left-leaves/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution(object): 8 | def sumOfLeftLeaves(self, root): 9 | """ 10 | :type root: TreeNode 11 | :rtype: int 12 | """ 13 | 14 | def dfs(root, isLeft): 15 | if not root: 16 | return 0 17 | if not root.left and not root.right: 18 | return root.val if isLeft else 0 19 | return dfs(root.left, True) + dfs(root.right, False) 20 | 21 | return dfs(root, False) 22 | -------------------------------------------------------------------------------- /Py/0566-reshape-the-matrix/solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def matrixReshape(self, mat, r, c): 3 | """ 4 | :type mat: List[List[int]] 5 | :type r: int 6 | :type c: int 7 | :rtype: List[List[int]] 8 | """ 9 | if len(mat) * len(mat[0]) != r * c: 10 | return mat 11 | 12 | reshape = [[]] 13 | for row in mat: 14 | for col in row: 15 | if len(reshape[-1]) < c: 16 | reshape[-1].append(col) 17 | else: 18 | reshape.append([]) 19 | reshape[-1].append(col) 20 | return reshape 21 | -------------------------------------------------------------------------------- /Py/0876-middle-of-the-linked-list/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution(object): 7 | def middleNode(self, head): 8 | """ 9 | :type head: ListNode 10 | :rtype: ListNode 11 | """ 12 | firstP = secoundP = head 13 | while secoundP != None: # move the secound pointer first and if it becomes None just return firstPointer 14 | secoundP = secoundP.next 15 | if secoundP == None: 16 | return firstP 17 | secoundP = secoundP.next 18 | firstP = firstP.next 19 | return firstP 20 | -------------------------------------------------------------------------------- /Py/1539-kth-missing-positive-number/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findKthPositive(self, arr: List[int], k: int) -> int: 3 | # Initialize two pointers, l (low) and h (high). 4 | l, h = 0, len(arr) - 1 5 | 6 | # Binary search loop to find the kth missing positive integer. 7 | while l <= h: 8 | # Calculate the middle index. 9 | mid = (l + h) // 2 10 | 11 | # Calculate the number of missing positive integers up to the middle element. 12 | missing = arr[mid] - (mid + 1) 13 | 14 | # If the number of missing positive integers up to mid is less than k, 15 | # move the left pointer (l) to mid + 1. 16 | if missing < k: 17 | l = mid + 1 18 | # Otherwise, move the right pointer (h) to mid - 1. 19 | else: 20 | h = mid - 1 21 | 22 | # After the binary search, l will be the index where the kth missing positive integer 23 | # would be if it existed in the array. We add k to it to get the actual missing integer. 24 | return l + k 25 | -------------------------------------------------------------------------------- /Py/189-rotate-array/solution1.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | """ 4 | Rotate the list 'nums' to the right by 'k' steps. 5 | 6 | Args: 7 | - nums (List[int]): List of integers to be rotated. 8 | - k (int): Number of steps to rotate the list. 9 | 10 | Returns: 11 | None. The list 'nums' is modified in-place. 12 | """ 13 | n = len(nums) 14 | ans = [0] * n # Initialize a list of zeros with size 'n' 15 | 16 | for i in range(n): 17 | ans[(i + k) % n] = nums[i] 18 | 19 | nums[:] = ans # Update the original 'nums' list with rotated values 20 | -------------------------------------------------------------------------------- /Py/189-rotate-array/solution2.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def rotate(self, nums: List[int], k: int) -> None: 5 | """ 6 | Do not return anything, modify nums in-place instead. 7 | """ 8 | n = len(nums) 9 | 10 | # Adjust 'k' to handle cases where 'k' is larger than 'n' 11 | k = k % n 12 | 13 | # Reverse the first part of the list (0 to n-k-1) 14 | nums[:n-k] = reversed(nums[:n-k]) 15 | 16 | # Reverse the second part of the list (n-k to n-1) 17 | nums[n-k:] = reversed(nums[n-k:]) 18 | 19 | # Reverse the entire list 20 | nums[:] = reversed(nums) 21 | -------------------------------------------------------------------------------- /Py/2301-manasa-and-factorials/problem.md: -------------------------------------------------------------------------------- 1 | # [Manasa and Factorials](https://www.hackerrank.com/challenges/manasa-and-factorials/problem) 2 | Manasa was sulking her way through a boring class when suddenly her teacher singled her out and asked her a question. He gave her a number n and Manasa has to come up with the smallest number m which contains atleast n number of zeros at the end of m!. Help Manasa come out of the sticky situation. 3 | 4 | ### Input Format 5 | The first line contains an integer T i.e. the number of Test cases. 6 | Next T lines will contain an integer n. 7 | 8 | ### Output Format 9 | Print smallest such number m. 10 | 11 | ### Constraints 12 | - 1 ≤ T ≤ 100 13 | - 1 ≤ n ≤ 1016 14 | 15 | ### Sample Input 16 | ``` 17 | 3 18 | 1 19 | 2 20 | 3 21 | ``` 22 | 23 | ### Sample Output 24 | ``` 25 | 5 26 | 10 27 | 15 28 | ``` 29 | 30 | ### Explanation 31 | 32 | As 4! = 24 and 5! = 120, so minimum value of m will be 5. 33 | 34 | As 9! = 362880 and 10! = 3628800, so minimum value of m will be 10. 35 | 36 | As 14! = 87178291200 and 15! = 1307674368000, so minimum value of m will be 15. -------------------------------------------------------------------------------- /Py/2405-optimal-partition-of-string/solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def partitionString(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | hashSet = set() 8 | subs = 1 # beacuse the last char if the case is aba for ex 9 | 10 | for i in s: 11 | if i in hashSet: 12 | subs += 1 13 | hashSet = set() # O(1) 14 | hashSet.add(i) 15 | else: 16 | hashSet.add(i) 17 | return subs 18 | -------------------------------------------------------------------------------- /Py/24548-repeated-string/solution.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | def repeatedString(s, n): 4 | # count the number of 'a' in string s 5 | total_a = s.count('a') 6 | 7 | # calculate the number of times s will be repeated 8 | b = n // len(s) 9 | 10 | # calculate the number of 'a' in the repeated string 11 | total_a = total_a * b 12 | 13 | # calculate the number of 'a' in the remaining string 14 | left = n % len(s) 15 | 16 | # find remaining substring 17 | sub_s = s[0:left] 18 | 19 | # add the number of 'a' in the remaining string to total_a 20 | total_a += sub_s.count('a') 21 | 22 | # return as result 23 | return total_a 24 | 25 | if __name__ == '__main__': 26 | s = input() 27 | 28 | n = int(input().strip()) 29 | 30 | result = repeatedString(s, n) 31 | 32 | print(str(result) + '\n') 33 | -------------------------------------------------------------------------------- /Py/2536-sherlock-and-divisors/problem.md: -------------------------------------------------------------------------------- 1 | # [Sherlock and Divisors (Easy)](https://www.hackerrank.com/challenges/sherlock-and-divisors/problem) 2 | Watson gives an integer to Sherlock and asks him: What is the number of divisors of that are divisible by 2?. 3 | 4 | ## Input Format 5 | First line contains , the number of testcases. This is followed by lines each containing an integer . 6 | 7 | ## Output Format 8 | For each testcase, print the required answer in one line. 9 | 10 | ## Constraints 11 | ``` 12 | 1 <= T <=100 13 | 1<= N <= 10^9 14 | ``` 15 | 16 | 17 | ## Sample Input 18 | ``` 19 | 2 20 | 9 21 | 8 22 | ``` 23 | 24 | ## Sample Output 25 | ``` 26 | 0 27 | 3 28 | ``` 29 | 30 | ## Explanation 31 | 9 has three divisors 1, 3 and 9 none of which is divisible by 2. 32 | 33 | 8 has four divisors 1,2,4 and 8, out of which three are divisible by 2. -------------------------------------------------------------------------------- /Py/5529-fliping-bits/solution.py: -------------------------------------------------------------------------------- 1 | # Create a function called flippingBits that takes an integer n as a parameter 2 | def flippingBits(n): 3 | # Just return the bitwise XOR of n and 2**32 - 1 4 | # 2**32 - 1 is the binary representation of 32 1s 5 | # XORing a number with 1 will flip the bits 6 | # with this way, we don't need to convert the number to binary 7 | # and decrase the time complexity 8 | return n ^ (2**32 - 1) 9 | 10 | if __name__ == '__main__': 11 | q = int(input().strip()) 12 | 13 | for q_itr in range(q): 14 | n = int(input().strip()) 15 | 16 | result = flippingBits(n) 17 | 18 | print(str(result) + '\n') -------------------------------------------------------------------------------- /Py/645-Set-Mismatch/problem.md: -------------------------------------------------------------------------------- 1 | # 645. Set Mismatch 2 | 3 | You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number. 4 | You are given an integer array `nums` representing the data status of this set after the error. 5 | Find the number that occurs twice and the number that is missing and return *them in the form of an array*. 6 | 7 | 8 | **Example 1:** 9 | **Input:** nums = [1,2,2,4] 10 | **Output:** [2,3] 11 | 12 | 13 | **Example 2:** 14 | 15 | **Input:** nums = [1,1] 16 | **Output:** [1,2] 17 | 18 | 19 | **Constraints:** 20 | 21 | - `2 <= nums.length <= 10^4` 22 | - `1 <= nums[i] <= 10^4` 23 | 24 | 25 | -------------------------------------------------------------------------------- /Py/645-Set-Mismatch/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findErrorNums(self, nums: List[int]) -> List[int]: 3 | # Calculate the duplicate by subtracting the sum of unique elements from the sum of all elements 4 | dupe = sum(nums) - sum(set(nums)) 5 | 6 | # Calculate the missing number by finding the expected sum of a sequence 7 | # from 1 to the length of the input list and subtracting the sum of unique elements 8 | miss = len(nums) * (len(nums) + 1) // 2 - sum(set(nums)) 9 | 10 | # Return a list containing the duplicate and missing numbers 11 | return [dupe, miss] -------------------------------------------------------------------------------- /images/PascalTriangleAnimated2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/images/PascalTriangleAnimated2.gif -------------------------------------------------------------------------------- /images/apple-orange.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/images/apple-orange.png -------------------------------------------------------------------------------- /images/book-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/images/book-1.png -------------------------------------------------------------------------------- /images/books.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/images/books.png -------------------------------------------------------------------------------- /images/container-with-most-water.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/images/container-with-most-water.jpg -------------------------------------------------------------------------------- /images/designer-pdf-viewer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/images/designer-pdf-viewer.png -------------------------------------------------------------------------------- /images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/images/logo.png -------------------------------------------------------------------------------- /images/sudoku-board.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JenilGajjar20/Competitive-Programming_problems/a5bc0a4a2e153e073afbc3772248220ed5309b4f/images/sudoku-board.png --------------------------------------------------------------------------------