0% found this document useful (0 votes)
57 views59 pages

DSA Practice Questions in C++

hi my name suraj mishra . dthetdhetrnetdnhtdhetdhethtehethrhrhrhrhrhrhrhrrherhtdhdhtdh

Uploaded by

surajmishrawork
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views59 pages

DSA Practice Questions in C++

hi my name suraj mishra . dthetdhetrnetdnhtdhetdhethtehethrhrhrhrhrhrhrhrrherhtdhdhtdh

Uploaded by

surajmishrawork
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

DSA Practice Questions

in C++
LeetCode Questions with Solution

Topic Covered
[ARRAY,SORTING,SEARCHING,STRING,DP,LINKED LIST]

@surajmishra8299
DAY-1

TOPIC - Array & Sorting Related Questions

LEVEL - Easy

268. Missing Number


Input: nums = [3,0,1]
Output: 2

Explain: Formula for finding missing number-


misNum = n(n+1)/2 - sumofElm(nums)

SOLUTION

@surajmishra8299
DAY-2

TOPIC - Array & Sorting Related Questions

LEVEL - Medium

179. Largest Number


Input: nums = [10,2]
Output: "210"

Explain: Sort the numbers based on their string


concatenations in different orders (e.g., a+b vs.
b+a). After sorting, the numbers are
concatenated into the final result, ensuring that
the largest possible number is formed. If the
result starts with 0, the answer should be 0.

SOLUTION

@surajmishra8299
DAY-3

TOPIC - Array & Sorting Related Questions

LEVEL - Medium

611. Valid Triangle Number


Input: nums = [2,2,3,4]
Output: 3
Explanation: Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
Here the triangle is valid if two of its side sum is greater
than the third side. to simplify it first sort sides. then from the
2nd index apply binary search over the left side of the array.
add each case's answers and return.

SOLUTION

@surajmishra8299
DAY-4

TOPIC - Array & Sorting Related Questions

LEVEL - Easy

561. Array Partition


Input: nums = [1,4,3,2]
Output: 4
Explanation: All possible pairings (ignoring
the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.

SOLUTION

@surajmishra8299
DAY-5

TOPIC - Array & Sorting Related Questions

LEVEL - Medium

164. Maximum Gap


Input: nums = [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is
[1,3,6,9], either (3,6) or (6,9) has the maximum
difference 3.
This code sorts the array and calculates the
largest difference between consecutive elements
in the sorted array. It handles edge cases where
the array has fewer than two elements by
returning 0.

SOLUTION

@surajmishra8299
DAY-6

TOPIC - Array & Sorting Related Questions

LEVEL - Easy

905. Sort Array By Parity


Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3],
and [4,2,1,3] would also be accepted.
This function rearranges the elements of the
vector A such that all even numbers come before
all odd numbers. It uses a two-pointer technique
to perform the sorting in-place.

SOLUTION

@surajmishra8299
DAY-7

TOPIC - Array, Sorting & Searching Related


Questions

LEVEL - Medium

378. Kth Smallest Element in a Sorted Matrix


Input: matrix = [[1,5,9],[10,11,13],[12,13,15]],
k=8
Output: 13
Explanation: The elements in the matrix are
[1,5,9,10,11,12,13,13,15], and the 8th smallest
number is 13
The code finds the k-th smallest element in a
given n x n matrix. It first flattens the matrix into
a single vector and then sorts the vector. Finally,
it returns the (k-1)-th element from the sorted
vector, or -1 if k is larger than the total number of
elements.

SOLUTION

@surajmishra8299
DAY-8

TOPIC - Array, Sorting & Searching Related


Questions

LEVEL - Easy

2089. Find Target Indices After Sorting Array


Input: nums = [1,2,5,2,3], target = 2
Output: [1,2]
Explanation: After sorting, nums is
[1,2,2,3,5]. The indices where nums[i] == 2 are 1
and 2.
This code defines a function targetIndices
that takes an array nums and a target value. It
first sorts the array, then iterates through the
sorted array to find all indices where the target
appears. These indices are stored in a vector k.
Finally, it returns the vector containing the target
indices.

SOLUTION

@surajmishra8299
DAY-9

TOPIC - Array, Sorting & Searching Related


Questions
LEVEL - Easy

1385. Find the Distance Value Between Two


Arrays
Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2
Explanation: For arr1[0] = 4 we have:
|4-10|=6 > d=2 , |4-9|=5 > d=2 , |4-1|=3 > d=2 , |4-8|=4 > d=2
For arr1[1]=5 we have:
|5-10|=5 > d=2 , |5-9|=4 > d=2 , |5-1|=4 > d=2 , |5-8|=3 > d=2
For arr1[2]=8 we have:
|8-10|=2 <= d=2 , |8-9|=1 <= d=2 , |8-1|=7 > d=2 , |8-8|=0 <= d=2
In this question defines a function findTheDistanceValue
that calculates how many elements in arr1 are at least a
distance d away from all elements in arr2. It iterates
through each element of arr1 and checks if the absolute
difference between the current element and any element
in arr2 is less than or equal to d. If no such close element
is found, the count is incremented. The function finally
returns the count of such elements.

SOLUTION
@surajmishra8299
DAY-10

TOPIC - Array, Sorting & Searching Related


Questions
LEVEL - Easy

2824. Count Pairs Whose Sum is Less than Target


Input: nums = [-1,1,2,3,1], target = 2
Output: 3
Explanation: There are 3 pairs of indices that
satisfy the conditions in the statement: - (0, 1) since
0 < 1 and nums[0] + nums[1] = 0 < target - (0, 2)
since 0 < 2 and nums[0] + nums[2] = 1 < target - (0,
4) since 0 < 4 and nums[0] + nums[4] = 0 < target.
This C++ code defines a function countPairs
that counts how many pairs of elements in the
nums array have a sum less than the given target.
It uses a nested loop to iterate through all unique
pairs of elements. If the sum of any two elements is
less than the target, it increments the ans counter.
Finally, it returns the total count of such pairs.

SOLUTION
@surajmishra8299
DAY-11

TOPIC - Array, Sorting & Searching Related


Questions
LEVEL - Easy

1337. The K Weakest Rows in a Matrix


Input: mat = [[1,1,0,0,0], [1,1,1,1,0], [1,0,0,0,0], [1,1,0,0,0],
[1,1,1,1,1]], k = 3
Output: [2,0,3]
Explanation: The number of soldiers in each row is:
- Row 0: 2
- Row 1: 4
- Row 2: 1
- Row 3: 2
- Row 4: 5
The rows ordered from weakest to strongest are [2,0,3,1,4].
In this code defines a function kWeakestRows that
identifies the k weakest rows in a matrix mat based on the
number of 1s in each row. It stores each row's soldier count
(number of 1s) and its index as pairs in a vector ans. The
vector is sorted by the count, and the indices of the k
weakest rows are extracted and stored in the result vector
res, which is returned as the output.

SOLUTION
@surajmishra8299
DAY-12

TOPIC - Array, Sorting & Searching Related


Questions
LEVEL - Easy

1608. Special Array With X Elements Greater Than


or Equal X
Input: nums = [0,4,3,0,4]
Output: 3
Explanation: There are 3 values that are greater
than or equal to 3.
In this question defines a function specialArray
that checks if there exists a number i such that
exactly i elements in the array nums are greater
than or equal to i. It iterates over possible values of
i from 0 to the array size n, counting elements that
meet the condition. If the count matches i, it returns
i. If no such i is found, it returns -1.

SOLUTION

@surajmishra8299
DAY-13

TOPIC - String Related Questions


LEVEL - Easy

3110. Score of a String


Input: s = "hello"
Output: 13
Explanation: The ASCII values of the
characters in s are: 'h' = 104, 'e' = 101, 'l' = 108,
'o' = 111. So, the score of s would be |104 - 101| +
|101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3
= 13.

SOLUTION

@surajmishra8299
DAY-14

TOPIC - String Related Questions


LEVEL - Easy

13. Roman to Integer


Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
In this question converts a Roman numeral
string into its integer equivalent. It uses an
unordered map to store the values of Roman
characters (I, V, X, etc.). The logic checks each
character in the string, and if the current
character's value is less than the next
character's value, it subtracts it; otherwise, it
adds the value to the result. Finally, the total
integer value is returned as ans.

SOLUTION

@surajmishra8299
DAY-15

TOPIC - String Related Questions


LEVEL - Medium

12. Integer to Roman


Input: num = 1994
Output: "MCMXCIV"
Explanation: 1000 = M , 900 = CM , 90 = XC , 4
= IV
In this code converts an integer to its
Roman numeral representation. It uses two
arrays: one for the values of Roman numerals
and the other for their corresponding symbols.
The while loop repeatedly subtracts the largest
possible Roman numeral value from num and
appends the corresponding Roman symbol to
the result string until num becomes zero. The
if-else statement ensures the program moves
through the numeral values correctly.

SOLUTION

@surajmishra8299
DAY-16

TOPIC - String Related Questions


LEVEL - Easy

14. Longest Common Prefix


Input: strs = ["flower","flow","flight"]
Output: "fl"
Explanation: In this code finds the longest
common prefix in an array of strings. It sorts the
array and compares the first and last strings, as
they will have the minimum common prefix after
sorting. A loop compares characters from both
strings until they differ, adding matching
characters to the result. The resulting common
prefix is returned.

SOLUTION

@surajmishra8299
DAY-17

TOPIC - String Related Questions


LEVEL - Easy

28. Find the Index of the First


Occurrence in a String
Input: haystack = "sadbutsad",needle ="sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6. The
first occurrence is at index 0, so we return 0.
In this code searches for the first occurrence
of the substring needle in the string haystack. If
the length of haystack is smaller than needle, it
returns -1. It iterates through haystack, checking
each substring of length equal to needle for a
match. If a match is found, it returns the index;
otherwise, it returns -1.

SOLUTION

@surajmishra8299
DAY-18

TOPIC - String Related Questions


LEVEL - Medium

151. Reverse Words in a String


Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not
contain leading or trailing spaces.
The code defines a function reverseWords
that takes a string s as input. It uses a
stringstream to extract words from the input
string one by one. For each word, it prepends
the word to the string a, building the sentence in
reverse order. After the loop, it removes the
trailing space from a and returns the reversed
sentence.

SOLUTION

@surajmishra8299
DAY-19

TOPIC - String Related Questions


LEVEL - Easy

168. Excel Sheet Column Title


Input: columnNumber = 28
Output: "AB"
Explanation: This code converts a given
integer c into its corresponding Excel column
title. It works by repeatedly subtracting 1 from c,
calculating the character for the last position (ch
= 'A' + c % 26), and then reducing c by dividing it
by 26. The characters are collected in reverse, so
they are reversed at the end to form the correct
title. Finally, the resulting string is returned.

SOLUTION

@surajmishra8299
DAY-20

TOPIC - String Related Questions


LEVEL - Easy

58. Length of Last Word


Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with
length 4.
The function finds the length of the last word
in a string. It first skips any trailing spaces, then
identifies the position where the last word ends.
Starting from there, it moves backward to find
where the last word begins. The difference
between the end and start positions gives the
length of the last word.

SOLUTION

@surajmishra8299
DAY-21

TOPIC - String Related Questions


LEVEL - Medium

3211. Generate Binary Strings Without Adjacent


Zeros
Input: n = 3
Output: ["010","011","101","110","111"]
Explanation: The valid strings of length 3 are:
"010", "011", "101", "110", and "111".
This code generates all binary strings of
length n where no two consecutive '1's appear.
The solve function is a recursive backtracking
function that builds valid strings. At each index,
if the previous character was '1', it appends '0',
ensuring no consecutive '1's, otherwise, it
appends both '0' and '1'. The validStrings
function initiates the process and returns all
valid strings stored in ans.

SOLUTION

@surajmishra8299
DAY-22

TOPIC - String Related Questions


LEVEL - Easy

125. Valid Palindrome


Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a
palindrome.
The code defines a function to check if a
given string is a palindrome, ignoring
non-alphanumeric characters and case
differences. It initializes two pointers, one at the
start and the other at the end of the string, and
iterates through the string while comparing
characters. Non-alphanumeric characters are
skipped, and case-insensitive comparisons are
made between valid characters. If a mismatch is
found, the function returns false, and if all
characters match, it returns true.

SOLUTION
@surajmishra8299
DAY-23

TOPIC - String Related Questions


LEVEL - Hard

899. Orderly Queue


Input: s = "cba", k = 1
Output: "acb"
Explanation: In the first move, we move the
1st character 'c' to the end, obtaining the string
"bac". In the second move, we move the 1st
character 'b' to the end, obtaining the final result
"acb".
The orderlyQueue function rearranges the
string s based on the value of k. If k > 1, it sorts
the string in lexicographical order and returns it.
When k == 1, it generates all possible cyclic
rotations of s by concatenating it with itself, then
returns the lexicographically smallest rotation.
This ensures the smallest possible arrangement
of characters depending on the constraints.

SOLUTION
@surajmishra8299
DAY-24

TOPIC - String Related Questions


LEVEL - Easy

171. Excel Sheet Column Number


Input: columnTitle = "ZY"
Output: 701
Explanation: This code converts an Excel
column title to its corresponding column
number. It initializes the result ans as 0 and
iterates through each character in the input
string. For each character, it multiplies ans by 26
(since there are 26 letters in the alphabet) and
adds the character's position in the alphabet
(where 'A' is 1, 'B' is 2, etc.). The final value of
ans is returned as the column number.

SOLUTION

@surajmishra8299
DAY-25

TOPIC - String Related Questions


LEVEL - Easy

205. Isomorphic Strings


Input: s = "egg", t = "add"
Output: true
Explanation: The strings s and t can be made
identical by: Mapping 'e' to 'a'. Mapping 'g' to 'd'.
The isIsomorphic function checks if two
strings, s and t, are isomorphic by comparing
their character mappings. It uses two arrays to
track the last seen index of each character in
both strings. As it iterates through the
characters, it ensures that the corresponding
characters in s and t have the same mapping. If
any mismatch occurs in their mappings, it
returns false; otherwise, it returns true after
completing the check.

SOLUTION

@surajmishra8299
DAY-26

TOPIC - String Related Questions


LEVEL - Easy

242. Valid Anagram


Input: s = "anagram", t = "nagaram"
Output: true
Explanation: This code checks if two strings
are anagrams by counting the frequency of
characters. It first increments the count of each
character in string s using a map, and then
decrements the count for characters in string t.
After processing both strings, it checks if all
character counts are zero in the map. If any
count is non-zero, it returns false, otherwise, it
returns true.

SOLUTION

@surajmishra8299
DAY-27

TOPIC - String Related Questions


LEVEL - Medium

139. Word Break


Input: s = "leetcode", wordDict =
["leet","code"]
Output: true
Explanation: Return true because "leetcode" can
be segmented as "leet code".
This code defines a function to check if a string
can be segmented into words from a dictionary. It
uses dynamic programming (dp array) where dp[i] is
true if the substring from index i to the end can be
broken into dictionary words. The function iterates
backward through the string, trying all possible
substrings starting at i. If a substring is found in the
dictionary, it checks if the remaining part of the string
can also be segmented. The loop stops early if a valid
segmentation is found. Finally, it returns whether the
entire string can be segmented (dp[0]).

SOLUTION
@surajmishra8299
DAY-28

TOPIC - String Related Questions


LEVEL - Easy

2900. Longest Unequal Adjacent Groups


Subsequence I
Input: words = ["e","a","b"], groups = [0,0,1]
Output: ["e","b"]
Explanation: A subsequence that can be selected is
["e","b"] because groups[0] != groups[2]. Another
subsequence that can be selected is ["a","b"] because
groups[1] != groups[2]. It can be demonstrated that
the length of the longest subsequence of indices that
satisfies the condition is 2.
This code finds a subsequence of words where
consecutive elements belong to different groups. It
iterates through the words vector and adds each word
to the result unless it's followed by another word from
the same group. If consecutive words belong to the
same group, it skips them. Finally, it returns the
subsequence of words with different group numbers.

SOLUTION
@surajmishra8299
DAY-29

TOPIC - Dynamic Programming Related


Questions
LEVEL - Easy

70. Climbing Stairs


Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
This code recursively calculates the number of ways
to climb n stairs, where you can take either 1 or 2
steps at a time. The solve function computes the
result for each step by summing the results for the
two previous steps, using memoization (dp array) to
store already computed values for efficiency. The
climbStairs function initializes the dp array and calls
solve to get the total number of ways for n steps. The
base case is when n is 0 or 1, where the result is 1, as
there's only one way to climb 0 or 1 steps.

SOLUTION
@surajmishra8299
DAY-30

TOPIC - Dynamic Programming Related


Questions
LEVEL - Easy

118. Pascal's Triangle


Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Explanation:

The code generates Pascal's Triangle by initializing a 2D


vector dp for n rows. Each row is resized to have the
correct number of elements, with the first and last
elements set to 1. For elements in between, it calculates
each value as the sum of the two values directly above it
from the previous row. Finally, the completed triangle is
returned as a 2D vector.

SOLUTION
@surajmishra8299
DAY-31

TOPIC - Dynamic Programming Related


Questions
LEVEL - Medium

120.Triangle
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
2
34
657
4183
The minimum path sum from top to bottom is 2 + 3 + 5 + 1
= 11 (underlined above).
The solution uses dynamic programming to find the
minimum path sum in a triangle. It builds a dp table,
where each element represents the minimum path
sum to reach that point. At each level of the triangle,
the value is updated by adding the minimum of the
possible paths from the previous level. Finally, the
minimum path sum of the last row is returned.

SOLUTION
@surajmishra8299
DAY-32

TOPIC - Dynamic Programming Related


Questions
LEVEL - Easy

338. Counting Bits


Input: n = 2
Output: [0,1,1]
Explanation: 0 --> 0 , 1 --> 1 , 2 --> 10
This code calculates the number of 1 bits in
binary representations for numbers from 0 to n.
It initializes a result vector ret where each index i
stores the count of 1 bits for that number. For
each integer i, it uses the expression i & (i - 1) to
refer to a previously computed number (which
has one less 1 bit than i). By adding 1 to this
previous result, it efficiently computes the bit
count for i. Finally, it returns the vector ret with
the counts for all numbers up to n.

SOLUTION

@surajmishra8299
DAY-33

TOPIC - Dynamic Programming Related


Questions
LEVEL - Medium

62. Unique Paths


Input: m = 3, n = 2
Output: 3
Explanation: From the top-left corner, there are a
total of 3 ways to reach the bottom-right corner: 1.
Right -> Down -> Down 2. Down -> Down -> Right 3.
Down -> Right -> Down
This code calculates the number of unique paths
in an 𝑚 × 𝑛 m×n grid, moving only down or right. It
uses a 1D array to store path counts for each column,
updating each cell by adding the count from the
previous cell in the same row. The outer loop iterates
over rows, and the inner loop iterates over columns,
updating path counts based on possible moves from
the left. The final value in the array represents the
total unique paths to reach the bottom-right corner.

SOLUTION
@surajmishra8299
DAY-34

TOPIC - Dynamic Programming Related


Questions
LEVEL - Medium

1641. Count Sorted Vowel Strings


Input: n = 1
Output: 5
Explanation: The 5 sorted strings that consist of
vowels only are ["a","e","i","o","u"].
This code calculates the number of
lexicographically sorted vowel strings of length n. It
initializes counts for each vowel and iteratively
updates them, where each vowel count depends on
the sum of itself and the counts of all vowels that can
come before it. This update process builds possible
strings of increasing length, ensuring they remain
lexicographically ordered. Finally, the count for the
vowel u holds the total number of valid strings of
length n, which is returned as the result.

SOLUTION

@surajmishra8299
DAY-35

TOPIC - Dynamic Programming Related


Questions
LEVEL - Easy

1668. Maximum Repeating Substring


Input: sequence = "ababc", word = "ab"
Output: 2
Explanation: "abab" is a substring in
"ababc".
This function calculates the maximum
number of consecutive times word repeats in
sequence. It iterates through sequence,
checking if each substring matches word. If
there's a match, it increments the count and
moves the index to the next non-overlapping
position. If there's a mismatch, it records the
maximum consecutive repetitions found, resets
the count, and slightly adjusts the index to allow
checking overlapping sections.

SOLUTION
@surajmishra8299
DAY-36

TOPIC - Dynamic Programming Related


Questions
LEVEL - Easy

1137. N-th Tribonacci Number


Input: n = 4
Output: 4
Explanation: T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
This code calculates the N-th Tribonacci
number using dynamic programming. It creates
a dp array where each element represents a
Tribonacci number, initializing dp[0] = 0 and all
others to 1. For each index from 3 to n, it
calculates the current Tribonacci number as the
sum of the previous three values. Finally, it
returns dp[n], which holds the N-th Tribonacci
number.

SOLUTION

@surajmishra8299
DAY-37

TOPIC - Dynamic Programming Related


Questions
LEVEL - Easy

1025. Divisor Game


Input: n = 2
Output: true
Explanation: Alice chooses 1, and Bob has no
more moves.
This function determines if Alice can win a game
with n stones, using a dynamic programming
approach. It creates an array, dp, where each element
represents whether Alice can win with that number of
stones. Starting from 2 stones, Alice wins because
she can take 1 and leave an odd number for Bob. For
each subsequent number of stones, the function
checks if there’s a divisor Alice can take, leaving Bob
in a position where he cannot win (i.e., dp[i - x] is
false). The function then returns the result for dp[n],
indicating if Alice wins with n stones.

SOLUTION
@surajmishra8299
DAY-38

TOPIC - Dynamic Programming Related


Questions
LEVEL - Easy

392. Is Subsequence
Input: s = "abc", t = "ahbgdc"
Output: true
Explanation: This code uses dynamic
programming to check if s is a subsequence of t by
calculating the longest common subsequence (LCS)
between them. It creates a 2D dp table, where dp[i][j]
represents the LCS length between the first i
characters of s and the first j characters of t. The table
is filled by comparing characters of s and t; if they
match, the LCS length is incremented, otherwise, the
maximum of excluding one character from either
string is taken. Finally, the code returns true if the LCS
length matches the length of s, indicating s is a
subsequence of t.

SOLUTION

@surajmishra8299
DAY-39

TOPIC - Dynamic Programming Related


Questions
LEVEL - Easy

746. Min Cost Climbing Stairs


Input: cost = [10,15,20]
Output: 15
Explanation: You will start at index 1. - Pay
15 and climb two steps to reach the top. The
total cost is 15.
The function calculates the minimum cost to
reach the top of a staircase, where each step has
a specific cost. It iterates from the third step
onward, updating each step’s cost to include the
minimum cumulative cost of the previous two
steps. After reaching the last step, it returns the
smaller of the costs for the last two steps,
representing the minimum cost to reach the top.

SOLUTION

@surajmishra8299
DAY-40

TOPIC - Dynamic Programming Related


Questions
LEVEL - Medium

64. Minimum Path Sum


Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1
minimizes the sum.

This code calculates the minimum path sum from the top-left to
the bottom-right corner of a grid by modifying the grid itself to
store cumulative path costs. Starting from the bottom-right cell, it
iterates backward to the top-left, updating each cell with the
minimum path sum possible to reach the target. Cells in the last
row or column can only add the cost of the cell to their right or
below, respectively, while other cells add the minimum of the
right or bottom cell. Finally, the top-left cell contains the
minimum path sum, which the function returns.

SOLUTION

@surajmishra8299
DAY-41

TOPIC - Dynamic Programming Related


Questions
LEVEL - Medium

1043. Partition Array for Maximum Sum


Input: arr = [1,15,7,9,2,5,10], k = 3
Output: 84
Explanation: arr becomes [15,15,15,9,10,10,10]
This code calculates the maximum possible sum
after partitioning an array arr into contiguous
subarrays of up to length k and changing each
subarray’s values to its maximum element. It
initializes a dynamic programming array dp of size
n+1 to store the best achievable sum up to each
position size in the array. For each index size, it
iterates over all possible partition lengths j up to k and
calculates the current maximum within that partition
(currmax), updating dp[size] with the maximum sum
achievable by adding this partition's contribution.
Finally, dp[n] holds the answer, representing the
maximum sum achievable for the entire array.

SOLUTION
@surajmishra8299
DAY-42

TOPIC - Dynamic Programming Related


Questions
LEVEL - Easy

121. Best Time to Buy and Sell Stock


Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on
day 5 (price = 6), profit = 6-1 = 5. Note that buying on
day 2 and selling on day 1 is not allowed because you
must buy before you sell.
The code calculates the maximum profit from a
single buy-sell transaction on given stock prices. It
first creates a maxPrices array to store the maximum
future price for each day, starting from the last day
and moving backward. Then, it iterates through each
day to calculate the potential profit by subtracting the
current day's price from the maximum future price and
updates the maximum profit accordingly. Finally, it
returns the highest possible profit.

SOLUTION

@surajmishra8299
DAY-43

TOPIC - Dynamic Programming Related


Questions
LEVEL - Easy

264. Ugly Number II


Input: n = 10
Output: 12
Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the
sequence of the first 10 ugly numbers.
The code finds the 𝑛 n-th ugly number, where ugly
numbers are positive integers with only 2, 3, or 5 as
their prime factors. It initializes a list with the first ugly
number, 1, and maintains pointers for multiples of 2, 3,
and 5. In each iteration, it calculates the next ugly
number by taking the minimum of the next multiples
of 2, 3, and 5, then increments the respective
pointer(s) if the minimum was generated by that
multiple. This process continues until the list contains
𝑛 n ugly numbers, and the 𝑛 n-th ugly number is
returned.

SOLUTION

@surajmishra8299
DAY-44

TOPIC - Linked List Related Questions


LEVEL - Easy

21. Merge Two Sorted Lists


Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Explanation:

The function mergeTwoLists recursively merges


two sorted linked lists by comparing their current
nodes. It checks if either list is empty, returning the
other if so. If the current node of list1 is smaller, it
recursively merges the rest of list1 with list2 and
returns list1. Otherwise, it does the same by merging
list1 with the rest of list2, returning list2.

SOLUTION
@surajmishra8299
DAY-45

TOPIC - Linked List Related Questions


LEVEL - Easy

83. Remove Duplicates from Sorted List


Input: head = [1,1,2]
Output: [1,2]
Explanation:

This code defines a function that removes


duplicates from a sorted singly-linked list. It uses a
pointer, curr, to traverse the list and checks if the
current node's value is equal to the next node's
value. If they are equal, it skips the next node by
updating the next pointer of the current node. If
they are not equal, it moves curr to the next node,
continuing until the end of the list is reached.
Finally, it returns the modified head of the list.

SOLUTION
@surajmishra8299
DAY-46

TOPIC - Linked List Related Questions


LEVEL - Easy

206. Reverse Linked List


Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Explanation:

The code reverses a singly linked list by iterating


through each node, starting from the head. It uses two
pointers, prev and curr, to reverse the direction of
each node's next pointer, so it points to the previous
node. As curr moves through the list, the next pointer
is updated to prev, effectively reversing the list one
node at a time. Once curr becomes NULL, the reversal
is complete, and prev becomes the new head of the
reversed list.

SOLUTION

@surajmishra8299
DAY-47

TOPIC - Linked List Related Questions


LEVEL - Easy

234. Palindrome Linked List


Input: head = [1,2,2,1]
Output: true
Explanation: The code defines a function
that checks if a singly-linked list is a palindrome.
It first traverses the list, storing the node values
in a vector. Then, it uses two pointers, one
starting from the left and the other from the right
of the vector, to compare the elements. If all
corresponding elements are equal, the list is a
palindrome; otherwise, it's not.

SOLUTION

@surajmishra8299
DAY-48

TOPIC - Linked List Related Questions


LEVEL - Medium

86. Partition List


Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
Explanation:

The code defines a function that partitions a


singly-linked list around a value 𝑥 x. It uses two
dummy nodes to create two separate lists: one for
nodes with values less than 𝑥 x and another for nodes
with values greater than or equal to 𝑥 x. After
traversing the original list, it connects the end of the
first list to the head of the second list and ensures the
second list ends with nullptr. Finally, it returns the
head of the modified list containing the partitioned
nodes.

SOLUTION
@surajmishra8299
DAY-49

TOPIC - Linked List Related Questions


LEVEL - Medium

19. Remove Nth Node From End of List


Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Explanation:

This code defines a function to remove the nth


node from the end of a singly-linked list. It uses a
dummy node to simplify edge cases and initializes
two pointers, first and second, both starting at the
dummy. The first pointer moves ahead by n + 1 steps,
and then both pointers advance until first reaches the
end, allowing second to point to the node before the
target node. Finally, the target node is removed by
adjusting the next pointer, and the function returns
the head of the modified list.

SOLUTION
@surajmishra8299
DAY-50

TOPIC - Linked List Related Questions


LEVEL - Medium

328. Odd Even Linked List


Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
Explanation:

The code rearranges a linked list by grouping


nodes at odd positions followed by nodes at even
positions. It initializes pointers for odd and even
nodes, then iterates through the list, adjusting their
next pointers to skip over even and odd nodes,
respectively. Once all nodes are grouped, the last odd
node is linked to the first even node. Finally, the
modified list is returned with odd-positioned nodes
preceding the even-positioned ones.

SOLUTION

@surajmishra8299
DAY-51

TOPIC - Linked List Related Questions


LEVEL - Medium

24. Swap Nodes in Pairs


Input: head = [1,2,3,4]
Output: [2,1,4,3]
Explanation:

The swapPairs method swaps adjacent nodes in a


singly-linked list by using a dummy node to simplify
the manipulation of the head. It iterates through the
list with two pointers, prev and curr, and for each pair
of nodes, it updates their pointers to perform the
swap. The second node of each pair becomes the new
head for that segment, while the first node points to
the next segment of nodes. Finally, it returns the
modified list starting from dummy.next, which points
to the new head.

SOLUTION
@surajmishra8299
DAY-52

TOPIC - Linked List Related Questions


LEVEL - Medium

61. Rotate List


Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Explanation:

The function rotateRight rotates a linked list to the


right by k positions. First, it calculates the list's length
and connects the last node to the head, forming a
circular list. It then updates k to k % length to reduce
unnecessary rotations and finds the new tail node by
moving length - k steps. Finally, it sets the new head
as temp->next, breaks the circular link, and returns
the rotated list.

SOLUTION
@surajmishra8299
DAY-53

TOPIC - Linked List Related Questions


LEVEL - Medium

237. Delete Node in a Linked List


Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node
with value 5, the linked list should become 4 -> 1
-> 9 after calling your function.
In this code, the deleteNode function
removes a given node from a singly-linked list.
Instead of deleting the node directly, it copies
the value of the next node into the current node,
making it effectively the next node. Then, it links
the current node to the node after the next one,
bypassing the original next node. This removes
the target node from the list without altering the
preceding nodes.

SOLUTION

@surajmishra8299
DAY-54

TOPIC - Linked List Related Questions


LEVEL - Medium

147. Insertion Sort List


Input: head = [4,2,1,3]
Output: [1,2,3,4]
Explanation: This code sorts a linked list by
first storing its values in a vector, sorting the
vector, and then rewriting the list nodes with the
sorted values. It starts by traversing the list to
push each node’s value into a vector. After
sorting the vector, it updates the original list
nodes with the sorted values from the vector.
Finally, the modified list (now sorted) is returned
as the result.

SOLUTION

@surajmishra8299
DAY-55

TOPIC - Linked List Related Questions


LEVEL - Medium

3217. Delete Nodes From Linked List Present in


Array
Input: nums = [1,2,3], head = [1,2,3,4,5]
Output: [4,5]
Explanation: The function modifiedList
removes nodes from a linked list if their values
are present in the given vector nums. It stores
the elements of nums in an unordered set s for
fast lookup. Using a dummy node, it traverses
the list, checking each node's value against the
set. If a node's value exists in the set, it
bypasses the node; otherwise, it moves to the
next node, returning the modified list at the end.

SOLUTION

@surajmishra8299
DAY-56

TOPIC - Linked List Related Questions


LEVEL - Easy

203. Remove Linked List Elements


Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Explanation: The code defines a function to
remove all nodes with a specific value from a
singly linked list. It starts by advancing the head
pointer past any nodes with the target value at
the beginning of the list. Then, it iterates through
the list, and if a node’s next node contains the
target value, it updates the pointer to skip that
node. The function returns the modified list
starting from the (possibly new) head.

SOLUTION

@surajmishra8299
DAY-57

TOPIC - Linked List Related Questions


LEVEL - Easy

148. Sort List


Input: head = [4,2,1,3]
Output: [1,2,3,4]
Explanation: The code takes the values from
each node in the linked list and stores them in a
vector. It then sorts the vector to arrange the
values in ascending order. A new sorted linked
list is created using the sorted values from the
vector. Finally, it returns the head of this new
sorted linked list.

SOLUTION

@surajmishra8299
DAY-58

TOPIC - Linked List Related Questions


LEVEL - Hard

23. Merge k Sorted Lists


Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[ 1->4->5,
1->3->4,
2->6 ]
merging them into one sorted list:
1->1->2->3->4->4->5->6
The code defines a function to merge multiple
sorted linked lists into one sorted list. It creates a
dummy node as the starting point, then iterates
through each list. For each node in a list, it finds
the correct position in the merged list, inserts the
node, and adjusts pointers to maintain sorted
order. Finally, it returns the merged list starting
from the first real node after the dummy.

SOLUTION
@surajmishra8299

You might also like