├── .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 |
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 |
29 | 1 <= strs.length <= 200
30 | 0 <= strs[i].length <= 200
31 | strs[i]
consists of only lowercase English letters.
32 |
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 |
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 |
19 | - 1 <= s.length <= 1000
20 | - s consists of only digits and English letters.
21 |
--------------------------------------------------------------------------------
/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 |
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 | 
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 | 
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 |
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