Abazie I. Data Structures & Algorithms For All Programmers 2023
Abazie I. Data Structures & Algorithms For All Programmers 2023
- Opeyemi Emmanuel
CEO/Founder (aiTSkillsCenter, Lagos
Algorithrr
for all programmers
Israel C. Abazie
What readers say...
II
What readers say...
III
What readers say...
IV
Foreword
V
In the subsequent section, readers
explore advanced algorithms, including
graph algorithms, dynamic programming,
and greedy algorithms. These advanced
techniques equip readers with
invaluable problem-solving strategies
for challenges such as finding the
shortest path and constructing minimum
spanning trees.
VI
him to create streamlined and intuitive
controls in his writing.
- Opeyemi Emmanuel
CEO/Founder @ITSkillsCenter, Lagos
VII
What to expect
o Dynamic Programming
o Recursion
° Graph
° Binary Tree
o Array
° Heaps
° Queue
IX
What to expect
o Graph Traversal
o Linked List
° Sorting
X
Table of contents
Beginner’s level
o Gray Code ........................................ 2
XI
Table of contents
Beginner’s level
o First Factorial ......................... 85
XII
Table of contents
Beginner’s level
o Container with Most Water .. 172
XIII
Table of contents
Beginner’s level
o Decode Ways ................................. 289
Advanced's level
o Recursive Backtracking ......... 308
o Amicable Pairs ........................... 315
o Deepcopy ........................................ 321
o Bracket Combinations ............. 326
o Minimum Number of Jumps .... 332
o Check for BST ............................. 339
o Left View of Binary Tree ... 346
o Remove Loop in Linked List . 353
o Detect Loop in Linked List . 360
o0-1 Knapsack Problem ......... 365
o Regular Expression ................ 372
o Remove Nth Node ................... 380
XIV
Table of contents
Advanced's level
o Merge K Sorted Lists ............. 385
o N-Queens ........................................ 396
o Permutation Sequence ............. 405
o Text Justification .................. 413
o Unique Binary Search Tree .. 439
o Validate BST ............................... 445
o Recover Binary Search Tree . 452
o Binary Tree Level Order .... 460
o Binary Zigzag Level Order .. 467
o Construct Binary Tree ........... 475
o Convert Sorted List to BST . 482
o Flatten Binary Tree ............... 498
XV
Table of contents
Advanced's level
o Word Ladder ................................ 533
o Largest Consecutive .............. 542
o Surrounded Regions ................. 549
o Palindrome Partitioning .... 558
o Gas Station ................................ 566
o Candy ............................................. 574
XVI
DSA Poem
XVII
Data Structures &
Algorithms
• for all programmers •
BEGINNER’S LEVEL
Beginner's level
DSA Challenge 1
Gray Code:
Write a function to encode a number to
and decode a number from Gray code.
The function should have 2 parameters.
The first would be a boolean and the
second parameter would be the number
to be encoded/decoded. The function
should encode for true and decode for
false.
Our logic:
2
Beginner's level
3
Beginner's level
4
Beginner's level
DSA Challenge 2
Minimum Substring:
Given an array 'strArr' with two
strings, *N’ and K', the
'MinWindowSubstring' function aims to
find the smallest substring in
that includes all characters from
'K'. For example: if strArr is
["aaabaaddae", "aed"] then the
smallest substring of 'N' that
contains the characters a, e, and d
is "dae" located at the end of the
string. So for this example your
program should return the string
' dae' .
Our logic:
The *MinWindowSubstring' function aims
to find the shortest substring in a
given string that includes all
characters from another given string.
It initializes the necessary variables
by extracting the first elements from
the input array.
6
Beginner's level
function MinWindowSubstring(strArr) {
let str = strArr[0];
let needle = strArr[1].split(1 1 );
for (let i = needle.length; i <=
str.length; i++ ) {
for (j =0; j <= str.length - i;
j++) {
let mySlice = str.substr(j, i);
if (isContained(mySlice)) {
return mySlice;
}
}
}
return false;
function isContained(str) {
let arr = str.split( ’ ’ );
for (let i = 0; i < needle.length;
i++) {
let place = arr.findlndex(val =>
{return val === needle[i]});
if (place === -1) {
return false;
7
Beginner's level
8
Beginner's level
9
Beginner's level
10
Beginner's level
DSA Challenge 3
FizzBuzz:
Write a program that generates an
array of integers from 1 to 100
(inclusive). But:
• for multiples of 3, add "Fizz" to
the array instead of the number
• for multiples of 5, add "Buzz" to
the array instead of the number
• for multiples of 3 and 5, add
"FizzBuzz" to the array instead of
the number
Your program should return an array
containing the results based on the
rules above.
Our logic:
function fizzBuzz() {
const result = [ ] ;
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
result.push("FizzBuzz") ;
} else if (i % 3 === 0) {
result.push("Fizz") ;
12
Beginner's level
} else if (i % 5 === 0) {
result.push("Buzz") ;
} else {
result.push(i);
return result;
}
console.log(fizzBuzz());
13
Beginner's level
14
Beginner's level
DSA Challenge 4
ABC Problem:
You are given a collection of ABC
blocks (e.g., childhood alphabet
blocks). There are 20 blocks with two
letters on each block. A complete
alphabet is guaranteed amongst all
sides of the blocks.
16
Beginner's level
Our logic:
function canMakeWord(word) {
const blocks = ['BO1, *XK', ’DQ1,
'CP', 'NA1, 'GT', 'RE1, ' TG', ' QD1 ,
'FS', 'JW, 'HU', VI', ‘ AN ' , 'OB',
'ER', ’FS’, 'LY', 'PC1, ’ZM'];
const usedBlocks = [];
word = word. tollpperCase() ;
for (let i = 0; i < word.length; i+
+) {
let foundBlock = false;
for (let j = 0; j < blocks.length;
j++) {
if (usedBlocks.includes(j))
continue;
if (blocks[j].includes(word[i]))
{
usedBlocks.push(j);
foundBlock = true;
break;
}
}
if (’foundBlock) return false;
}
return true;
}
17
Beginner's level
18
Beginner's level
DSA Challenge 5
Balanced Brackets:
Determine whether a generated string
of brackets is balanced; that is,
whether it consists entirely of pairs
of opening/closing brackets (in that
order), none of which mis-nest.
Examples:
Input Output
[] true
][ false
[][] true
][] false
[]][[] false
[[[[]]]] true
20
Beginner's level
Our logic:
One way to solve this problem is to
use a stack data structure. We can
iterate over the string of brackets,
and for each opening bracket we
encounter, we push it onto the stack.
For each closing bracket, we pop the
most recent opening bracket from the
stack and check if they match. If they
don't match, or if we encounter a
closing bracket before we've seen any
opening brackets, then the string is
not balanced.
Here's one possible implementation in
JavaScript:
function isBalanced(str) {
const stack = [ ];
const opening = [ ’ [ ' , ' {1, ' (' ] ;
const closing = [']',
for (let i = 0; i < str.length; i+
+) {
const char = str[i] ;
if (opening.includes(char)) {
stack.push(char);
} else if
(closing.includes(char)) {
21
Beginner's level
const lastOpening =
stack.pop();
if
(opening.indexOf(lastOpening) !==
closing.indexOf(char)) {
return false;
}
}
return stack.length === 0;
}
console.log(isBalanced("[]")) //true
console.log(isBalanced("]][[[][][][]]
[")) //false
22
Beginner's level
23
Beginner's level
24
Beginner's level
DSA Challenge 6
Sample inputs:
26
Beginner's level
Our logic:
}
const a = (r ** 2 - d ** 2 / 4)I **
0.5;
const xm = (xl + x2) / 2;
const ym = (y1 + y2) / 2;
const xcl = xm + a * (y2 - yi) / d;
const ycl = ym + a * (xl - x2) / d;
const xc2 = xm -a * (y2 - yi) / d;
const yc2 = ym -a * (xl - x2) / d;
return [
[xc1.toFixed(4), yc1.toFixed(4)],
[xc2.toFixed(4), yc2.toFixed(4)],
I;
}
console.log(findCircles([0.1234,
0.9876], [0.8765, 0.2345], 2.0))
28
Beginner's level
29
Beginner's level
30
Beginner's level
DSA Challenge 7
100 Doors:
There are 100 doors in a row that are
all initially closed. You make 100
passes by the doors. The first time
through, visit every door and
'toggle1 the door (if the door is
closed, open it; if it is open, close
it). The second time, only visit
every 2nd door (i.e., door #2, #4,
#6, ...) and toggle it. The third
time, visit every 3rd door (i.e.,
door #3, #6, #9, ...), etc., until
you only visit the 100th door.
Implement a function to determine the
state of the doors after the last
pass. Return the final result in an
array, with only the door number
included in the array if it is open.
Our logic:
function toggleDoors() {
let doors = Array(100).fill(false) ;
32
Beginner's level
doors[j] = !doors[j];
}
}
return openDoors;
>
33
Beginner's level
34
Beginner's level
DSA Challenge 8
Date manipulation:
Given a date string in EST, output
the given date as a string with 12
hours added to the time. Time zone
should be preserved.
Our logic:
function add12Hours(dateString) {
const months = [‘January’, ‘February1,
‘March', 'April', 'May', 'June',
'July', 'August', 'September',
'October', 'November1, 'December'];
// Get the parts of the string
const parts = datestring.split(' ');
const month =
months.indexOf(parts[0]);
const day = parselnt(parts[ 1 ], 10);
const year = parselnt(parts[2], 10);
const time = parts[3].split(’:');
36
Beginner's level
37
Beginner's level
console.log(add12Hours("March 6 2009
7:30pm EST"))
38
Beginner's level
39
Beginner's level
40
Beginner's level
DSA Challenge 9
42
Beginner's level
Our logic:
43
Beginner's level
The function
'generateOutputString(words)' takes
an input parameter words which is an
array of strings. It then generates
an output string based on the number
of input words according to the rules
specified in the problem statement.
Here's how the function works:
1. We initialize the output string as
output = ".
2. We then check the length of the
input words array to determine
which of the four cases we need to
handle.
44
Beginner's level
45
Beginner's level
46
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 10
Our logic:
48
Beginner's level
49
Beginner's level
50
Beginner's level
51
Beginner's level
52
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 11
Our 1Dflic:
function countChange(cents) {
let count = 0;
54
Beginner's level
return count;
}
55
Beginner's level
56
Beginner's level
57
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 12
Longest Word:
Have the function
longestWord(vintage) take the vintage
parameter being passed and return the
longest word in the string. If there
are two or more words that are the
same length, return the first word
from the string with that length.
Ignore punctuation and assume vintage
will not be empty. Words may also
contain numbers, for example "Hello
world123 567"
Our logic:
function longestWord(vintage) {
let words = vintage.split(" ");
let result =
for (let i = 0; i < words.length;
i++) {
if (words[i].length >
result.length) {
result = words[i];
}
59
Beginner's level
}
return result;
}
console.log(longestWord("Tech Dev
ITSkillsCenter"));
68
Beginner's level
61
Beginner's level
62
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 13
Our loi-ic:
class Num {
constructor(value) {
if (typeof value !== 'number' ||
isNaN(value)) {
throw new TypeError(1 Not a
Number');
}
if (value < 1 || value > 10) {
throw new TypeError(1 Out of
range' );
64
Beginner's level
}
this.value = value;
}
valueOf() {
return this.value;
toString() {
return St ring(this.value);
}
plus(num) {
return new Num(this.value +
num.value) ;
}
minus(num) {
return new Num(this.value -
num.value);
}
times(num) {
return new Num(this.value *
num.value);
}
65
Beginner's level
dividedBy(num) {
return new Num(this.value /
num.value);
)
modulo(num) {
return new Num(this.value %
num.value);
}
}
// Examples
const num1 = new Num(5);
console.log(numl.plus(new Num(3)));
// Output: 8
66
Beginner's level
try {
const num7 = new Num(’not a
number 1);
} catch (error) {
console.log(error.message); //
Output: Not a Number
}
67
Beginner's level
68
Beginner's level
69
Beginner's level
70
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 14
Hint:
If the array is [3, 5, 2, -4, 8, 11]
and the sum is 7 , your program
should return [[11, -4], [2, 5]]
because 11 + -4 = '7' and 2 + 5 = '7'
Our logic:
72
Beginner's level
if (visitedNums.has(complement))
pairs.push([num, complement]);
}
visitedNums.add(num);
}
return pairs;
}
73
Beginner's level
74
Beginner's level
75
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 15
Find Intersection:
Have the function
Findintersection(strArr) read the
array of strings stored in strArr
which will contain 2 elements: the
first element will represent a list
of comma-separated numbers sorted in
ascending order, the second element
will represent a second list of
comma-separated numbers (also
sorted). Your goal is to return a
comma-separated string containing the
numbers that occur in elements of
strArr in sorted order. If there is
no intersection, return the string
false.
Example:
Input: ["1, 3, 4, 7, 13", "1, 2, 4,
13, 15"]
Output: 1,4,13
Input: ["1, 3, 9, 10, 17, 18", "1, 4,
9, 10"]
Output: 1,9,10
77
Beginner's level
Our logic:
function Findlntersection(strArr) {
const [listl, list2] = strArr.map(str
=> str.split(", ").map(Number));
const intersection = [] ;
let i = 0, j =0;
while (i < listl.length && j <
list2.length) {
if (listl[i] === list2[j]) {
intersection.push(listl[i]) ;
i++ (
j++;
} else if (listl[i] < list2[j]) {
1++ j
} else {
j++;
}
console.log(Findlntersection(["1, 3,
4, 7, 13", "1, 2, 4, 13, 15"]));
78
Beginner's level
79
Beginner's level
80
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 16
First Reverse:
Have the function ’FirstReverse(str)‘
take the 'str' parameter being passed
and return the string in reversed
order.
Our logic:
function FirstReverse(str) {
return
str.split('1).reverse().join('');
}
82
Beginner's level
83
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 17
First Factorial:
Have the function FirstFactorial(num)
take the num parameter being passed
and return the factorial of :t. For
example: if num = 4, then your
program should return (4 * 3 * 2 * 1)
= 24. For the test cases, the range
will be between 1 and 18 and the
input will always be an integer.
Our logic:
Here's the code for the
FirstFactorial function in
JavaScript:
function FirstFactorial(num) {
if (num === 0 || num === 1) {
return 1;
}
return num * FirstFactorial(num -
i);
85
Beginner's level
86
Beginner's level
87
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 18
Our logic:
Here's a JavaScript program that
finds the missing element in an array
of size N-1 containing distinct
integers in the range of 1 to N:
function findMissingElement(arr, n)
{
let sum = (n * (n + 1)) / 2; //
Calculate sum of all elements from 1
to n
let missingElement = sum -
arr.reduce((acc, curr) => acc +
curr); // Subtract sum of array
elements from the sum of all elements
to find the missing element
return missingElement;
}
89
Beginner's level
90
Beginner's level
91
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 19
Kadane Algorithm:
Given an array Arr[] of N integers.
Find the contiguous sub
array (containing at least one number)
which has the maximum sum and return
its sum.
Your Task:
You don't need to read input or print
anything. The task is to complete the
function maxSubarraySum() which takes
Arr[] and N as input parameters and
returns the sum of subarray with
maximum sum.
Our logic:
function maxSubarraySum(Arr, N) {
let maxSoFar = Arr[0];
let maxEndingHere = Arr[0];
for (let i = 1; i < N; i++) {
maxEndingHere =
Math.max(maxEndingHere + Arr[i],
Arr[i]);
93
Beginner's level
maxSoFar = Math.max(maxSoFar,
maxEndingHere);
}
return maxSoFar;
}
94
Beginner's level
95
Beginner's level
96
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 20
Your Task:
You don't need to read input or print
anything. Your task is to complete
the function sort012() that takes an
array arr and N as input parameters
and sorts the array in-place.
Our logic:
Here's a JavaScript program that
sorts an array of 0s, Is, and 2s in
ascending order using the "Dutch
National Flag" algorithm:
function sort012(arr, n) {
let low = 0;
let mid = 0;
let high = n - 1 ;
98
Beginner's level
if (arr[mid] === 0) {
[arr[low], arr[mid]] =
[arr[mid], arr[low]];
low++;
mid++;
} else if (arr[mid] === 1) {
mid++;
} else if (arr[mid] === 2) {
[arr[mid], arr[high]] =
[arr[high], arr[mid]];
high--;
>
}
99
Beginner's level
100
Beginner's level
101
Beginner's level
102
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 21
Majority Element:
Given an array A of N elements. Find
the majority element in the array. A
majority element in an array A of
size N is an element that appears
more than N/2 times in the array.
Your Task:
The task is to complete the function
'majorityElement()' which returns the
majority element in the array. If no
majority exists, return '-1'.
Our logic:
function majorityElement(arr, n) {
let count = 0;
let candidate = 0;
104
Beginner's level
105
Beginner's level
106
Beginner's level
107
Beginner's level
DSA Challenge 22
Your Task:
Write a function called duplicates()
wh^ch takes array ’a[] ' and ’n' as
input as parameters and returns a
list of elements that occur more than
once in the given array in a sorted
manner. If no such element is found,
return list containing [-1].
Our logic:
function duplicates(arr, n) {
let result = [];
let freq = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
109
Beginner's level
freq[arr[i]]++;
}
}
if (result.length === 0) {
result.push(-1);
110
Beginner's level
111
Beginner's level
112
Beginner's level
113
Beginner's level
DSA Challenge 23
Count Inversions:
Given an array of integers. Find the
Inversion Count in the array.
Our logic:
function inversioncount(arr, N) {
let count = 0;
mergeSort(arr, 0, N - 1);
return count;
115
Beginner's level
function mergeSort(arr, 1, r) {
if (1 < r) {
let mid = Math.floor((1 + r) /
2);
mergeSort(arr, 1, mid);
mergeSort(arr, mid + 1, r) ;
merge(arr, 1, mid, r);
}
}
116
Beginner's level
}
for (let j = 0; j < n2; j++) {
R[ j ] = arr[mid + 1 + j ];
let i = 0,
j = 0,
k = 1;
117
Beginner's level
arr[k++] = R[j++];
count += n1 - i;
}
}
while (i < nl) {
arr[k++] = L[i++];
}
while (j < n2) {
arr[k++] = R[j++];
}
}
118
Beginner's level
119
Beginner's level
120
Beginner's level
121
Beginner's level
DSA Challenge 24
Our lo ic:
function trappingWater(arr, n) {
let result = 0;
let leftMax = 0;
let rightMax = 0;
let left = 0;
let right = n - 1 ;
while (left <= right) {
if (arr[left] < arr[right]) {
if (arr[left] > leftMax) {
123
Beginner's level
leftMax = arr[left];
}
left++ ;
} else {
if (arr[right] > rightMax) {
rightMax = arr[right];
} else {
result += rightMax -
arr[right];
}
right--;
}
}
return result;
}
124
Beginner's level
125
Beginner's level
DSA Challenge 25
Minimum Platforms:
Given arrival and departure times of
all trains that reach a railway
station. Find the minimum number of
platforms required for the railway
station so that no train is kept
waiting.Consider that all the trains
arrive on the same day and leave on
the same day. Arrival and departure
time can never be the same for a
train but we can have arrival time of
one train equal to departure time of
the other. At any given instance of
time, same platform can not be used
for both departure of a train and
arrival of another train. In such
cases, we need different platforms.
127
Beginner's level
Our logic:
Here is the javascript program using
the given function to find the minimum
number of platforms required at a
railway station:
128
Beginner's level
let platformsNeeded = 1 ;
let platformsOccupied = 1 ;
// Start from the second train and
check if there is a clash with the
previous train.
let i = 1 ;
let j = 0;
while (i < n && j < n) {
if (arr[i] <= dep[j ]) {
// If the current train arrives
before the previous train departs,
// a new platform is needed.
platformsNeeded++;
if (platformsNeeded >
platformsOccupied) {
129
Beginner's level
} else {
// If the current train arrives
after the previous train departs,
// the previous platform is
freed up and can be used again.
platformsNeeded--;
j++;
}
}
return platformsOccupied;
130
Beginner's level
131
Beginner's level
132
Beginner's level
DSA Challenge 26
Prak element:
An element is called a peak element
if its value is not smaller than the
value of its adjacent elements(if
they exists).Given an array arr[] of
size N, Return the index of any one
of its peak elements.Note: The
generated output will always be 1 if
the index that you return is correct.
Otherwise output will be 0.
Our logic:
function peakElement(arr, N) {
// Check if first or last element is
peak
134
Beginner's level
return i;
}
}
// No peak found
return -1;
135
Beginner's level
136
Beginner's level
137
Beginner's level
DSA Challenge 27
Common Elements:
Given three arrays sorted in
increasing order. Find the elements
that are common in all three arrays.
Our logic:
function commonElements(A, B, C) {
const common = [];
let i = 0,
j = 0.
k = 0;
139
Beginner's level
k++;
} else if (A[i] <= B[j] && A[i] <=
C[k]) {
1++ ,
J I
} else {
140
Beginner's level
k++;
}
}
return common;
141
Beginner's level
142
Beginner's level
143
Beginner's level
DSA Challenge 28
Example:
145
Beginner's level
Our logic:
+) {
obj[keys[i ] ] = vals[i];
}
return obj;
146
Beginner's level
147
Beginner's level
148
Beginner's level
DSA Challenge 30
Average Salary:
You are given an array of unique
integers salary where salary[i] is
the salary of the ith employee.
Our logic:
function
calculateAverageSalary(sala ry) {
// Sort the salary array in
ascending order
salary.sort(function(a, b) { return
a - b; });
// Remove the minimum and maximum
salaries from the array
150
Beginner's level
salary.shift();
salary.pop();
let sum = 0;
for (let i = 0; i < salary.length;
i++) {
sum += salary[i];
}
let average = sum / salary.length;
return average;
151
Beginner's level
152
Beginner's level
153
Beginner's level
DSA Challenge 31
Our logic:
To find the median of two sorted
arrays 'numsl' and 'nums2', you can
combine the arrays and then sort
them. The median of the combined
array can then be determined based on
whether the total number of elements
is even or odd.
155
Beginner's level
function
findMedianSortedArrays(nums1, nums2) {
const combined = [...numsl,
...nums2].sort((a, b) => a - b);
const total = combined.length;
const middle = Math.floor(total /
2);
if (total % 2 === 0) {
return (combined[middle] +
combined[middle - 1]) / 2;
} else {
return combined[middle] ;
}
}
156
Beginner's level
157
Beginner's level
• in a certain region.
3. Healthcare: In the medical field,
the median is used to analyze data
related to patient outcomes and to
evaluate the effectiveness of
treatments. For example, this
algorithm might be used to
calculate the median length of stay
for patients in a hospital or to
analyze the median survival time
for patients with a certain
disease.
158
Beginner's level
DSA Challenge 32
Our logic:
To find the longest palindromic
substring in a given string s', we
can use the following algorithm:
1 . Create a variable
'maxPalindromicSubstring' and set
it to an empty string.
2. Loop through each character in the
string 's':
a. For each character, consider it as
the center of a potential palindromic
substring.
b. Expand the potential palindromic
substring outward from the center
until it is no longer a palindrome.
160
Beginner's level
function
longestPalindromicSubstring(s) {
let maxPalindromicSubstring = ’';
for (let 1=0; i < s.length; i++) {
// odd-length palindromes
let left = i, right = i;
161
Beginner's level
right++;
}
let oddLengthPalindrome =
s.slice(left + 1, right);
// even-length palindromes
left = i;
right = i + 1 ;
while (left >= 0 && right <
s.length && s[left] === s[right]) {
left--;
right++;
}
let evenLengthPalindrome =
s.slice(left + 1, right);
if (oddLengthPalindrome.length >
maxPalindromicSubstring.length) {
maxPalindromicSubstring =
162
Beginner's level
oddLengthPalindrome;
}
if (evenLengthPalindrome.length >
maxPalindromicSubstring.length) {
maxPalindromicSubstring =
evenLengthPalindrome;
}
}
return maxPalindromicSubstring;
163
Beginner's level
164
Beginner's level
DSA Challenge 33
Reverse Integer:
Given a signed 32-bit integer x,
return x with its digits reversed. If
reversing x causes the value to go
outside the signed 32-bit integer
range [-231, 231 - 1], then return 0.
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
166
Beginner's level
Our logic:
function reverse(x) {
let reversed = 0;
const isNegative = x < 0;
x = Math.abs(x);
while (x > 0) {
reversed = reversed * 10 + x % 10;
x = Math.floor(x / 10);
if (reversed >2**31 - 1) {
return 0;
}
return isNegative ? -reversed :
reversed;
167
Beginner's level
168
Beginner's level
168
Beginner's level
169
Beginner's level
170
Beginner's level
DSA Challenge 34
Our Ionic:
function maxArea(height) {
let maxArea = 0;
let left = 0;
let right = height.length - 1;
172
Beginner's level
{
left++;
} else {
right--;
}
}
return maxArea;
173
Beginner's level
174
Beginner's level
175
Beginner's level
176
Beginner's level
DSA Challenge 35
Integer to Roman:
Roman numerals are represented by
seven different symbols: 'I', 'V',
'X', 'L', 'C', D' and 'M'.
Symbol Value
I 1
V 5
X 10
L. 50
C 100
D 500
M 1000
178
Beginner's level
Our logic:
function intToRoman(num) {
const values [1000, 900, 500, 400,
100, 90, 50, 40, 10,
const symbols "CM", D",
CD", "XC", " XL", "X", "IX",
V", "IV",
179
Beginner's level
}
}
return romanNumeral;
180
Beginner's level
181
Beginner's level
182
Beginner's level
DSA Challenge 36
Example 1 :
Input: strs =
["flower"/flow" /’flight” ]
Output: "fl"
Example 2:
184
Beginner's level
Our logic:
function longestCommonPrefix(strs) {
i++) {
while (strs[i].indexOf(prefix)
!== 0) {
prefix =
prefix.substring(0, prefix.length -
D;
if (prefix === "") return
Illi •
I
}
return prefix;
185
Beginner's level
186
Beginner's level
187
Beginner's level
188
Beginner's level
DSA Challenge 37
3Sum:
Given an integer array nums, return
all the triplets [nums[i]f numsfj],
nums[k]] such that i != j, i != k(
and j != k, and nums[i] + nums[j] +
nums[k] == 0.
Notice that the solution set must not
contain duplicate triplets.
Example:
(-1) = 0-
nums[0] + nums[3] + nums[4] = (-1) + 2
+ (-1) = 0.
190
Beginner's level
Our logic:
function threeSum(nums) {
nums.sort((a, b) => a - b);
let res = [ ] ;
for (let i = 0; i < nums.length -
2; i++) {
if (i === 0 || (i > 0 && nums[i] !==
nums[i - 1])) {
191
Beginner's level
let lo = i + 1 ;
let hi = nums.length - 1;
let sum = 0 - nums[i];
while (lo < hi) {
if (nums[lo] +
nums[hi] === sum) {
res.push([nums[i](
nums[lo], nums[hi]]);
while (lo < hi &&
nums[lo] === nums[lo +1]) lo++;
while (lo < hi &&
nums[hi] === nums[hi - 1]) hi--;
lo++;
hi--;
192
Beginner's level
let lo = i + 1 ;
let hi = nums.length - 1;
let sum = 0 - nums[i];
while (lo < hi) {
if (nums[lo] +
nums[hi] === sum) {
res.push([nums[i](
nums[lo], nums[hi]]);
while (lo < hi &&
nums[lo] === nums[lo +1]) lo++;
while (lo < hi &&
nums[hi] === nums[hi - 1]) hi--;
lo++;
hi--;
193
Beginner's level
10++ •
} else {
hi--;
}
}
}
}
return res;
194
Beginner's level
195
Beginner's level
196
Beginner's level
DSA Challenge 38
4Sum:
Given an array nums of n integers,
return an array of all the unique
quadruplets [nums[a], nums[b],
nums[c], nums[d]] such that:
• C <= a, b, c, d < n
• a, b, c, and d are distinct.
• nums[a] + nums[b] + nums[c] +
nums[d] == target
You may return the answer in any
order.
Our logic:
198
Beginner's level
left++;
right--;
} else if (sum < target) {
left++;
199
Beginner's level
else {
right--;
}
}
}
}
return Array.from(result).map(item
=> item.split(1,*).map(num =>
parselnt(num)));
200
Beginner's level
201
Beginner's level
202
Beginner's level
DSA Challenge 39
204
Beginner's level
Our logic:
function letterCombinations(digits) {
if (digits.length === 0) return [];
const map = {
};
function backtrack(index, current) {
if (index === digits.length) {
result.push(current);
205
Beginner's level
return;
}
const letters =
map[digits[index]];
for (let i = 0; i <
letters.length; i++) {
backtrack(index + 1, current +
letters[i]);
}
}
const result = [ ] ;
backtrack(0, ’1);
return result;
}
206
Beginner's level
207
Beginner's level
208
Beginner's level
DSA Challenge 40
210
Beginner's level
Our logic:
One possible solution for this
problem is to use bit manipulation to
perform the division operation
without using multiplication,
division, and mod operators.
return 2147483647;
}
const isNegative = (dividend < 0) !==
(divisor < 0);
211
Beginner's level
let quotient = 0;
for (let i = 31; i >= 0; i--) {
if ((dividend >>> i) - divisor
>= 0) {
quotient |= (1 << i);
dividend -= (divisor <<
i):
quotient;
212
Beginner's level
213
Beginner's level
214
Beginner's level
• moving objects.
4. Scientific computing: In scientific
computing, the algorithm is used to
solve complex mathematical
equations and perform numerical
simulations. It is used in a wide
range of fields, including physics,
chemistry, biology, and economics.
215
Beginner's level
DSA Challenge 41
Next Permutation:
Given an array of integers ’nurns',
find the next permutation of 'nurns'.
For example:
217
Beginner's level
Our logic:
To find the next permutation of an
array of integers nums, we can follow
the below steps:
1. Traverse the array from right to
left and find the first element
nums[i] such that nums[i] <
nums[i+1].
2. If no such element exists, it means
that we have reached the last
permutation of the given array. In
this case, we can simply reverse
the array to get the first
permutation.
3. If such an element exists, we need
to find the smallest element in the
subarray nums[i+1:] which is
greater than nums[i]. We swap these
two elements.
4. Finally, we reverse the subarray
nums[i+1:] to get the
lexicographically next greater
permutation.
218
Beginner's level
function nextPermutation(nums) {
let i = nums.length - 2;
// Find the first element i such
that nums[i] < nums[i+l]
while (i >= 0 && nums[i] >=
nums[i+1]) {
i--;
}
if (i >= 0) {
// Find the smallest element in
nums[i+1:] which is greater than
nums[i ‘
let j = nums.length - 1;
while (j >= 0 && nums[j] <=
nums[i]) {
219
Beginner's level
>
// Reverse the subarray nums[i+1:]
let left = i + 1 ;
let right = nums.length - 1;
while (left < right) {
[nums[left], nums[right]] =
[nums[right], nums[left]];
left++;
right--;
return nums;
220
Beginner's level
221
Beginner's level
222
Beginner's level
DSA Challenge 42
Our logic:
function searchRotatedArray(nums,
target) {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
224
Beginner's level
/ 2);
if (nums[mid] === target) {
return mid;
}
if (nums[left] <= nums[mid]) {
if (target >= nums[left] &&
target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1 ;
}
} else {
if (target > numsfmid] && target
<= nums[right]) {
left = mid + 1;
} else {
225
Beginner's level
right = mid - 1;
}
}
}
return -1;
226
Beginner's level
227
Beginner's level
228
Beginner's level
DSA Challenge 43
Our logic:
To solve this problem with 0(log n)
runtime complexity, we can use the
binary search algorithm. Here's a
JavaScript implementation:
230
Beginner's level
right) / 2);
if (numsfmid] === target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1 ;
} else {
right = mid - 1 ;
return left;
231
Beginner's level
232
Beginner's level
233
Beginner's level
234
Beginner's level
235
Beginner's level
DSA Challenge 44
Our logic:
Here's a JavaScript implementation of
the countAndSay function:
function countAndSay(n) {
if (n === 1) {
return "1";
237
Beginner's level
i++) {
if (prevTerm[i] === prevTerm[i +
1]) {
count++;
} else {
result += count + prevTerm[i];
count = 1 ;
}
}
return result;
238
Beginner's level
239
Beginner's level
240
Beginner's level
241
Beginner's level
DSA Challenge 45
Rotate Image:
You are given an n x n 2D matrix
representing an image, rotate the
image by 90 degrees (clockwise).
Our logic:
Here's the function to rotate a given
n x n matrix by 90 degrees clockwise:
function rotatelmage(matrix) {
const n = matrix.length;
// Transpose the matrix
243
Beginner's level
}
}
// Reverse each row
for (let i = 0; i < n; i++) {
for (let j = 0; j < n / 2; j++) {
const temp = matrix[i ] [j ] ;
matrix[i] [ j] = matrix[i][n - 1 -
J]>
matrix[i][n - 1 - j] = temp;
}
}
244
Beginner's level
1 2 3
4 5 6
7 8 9
1 4 7
2 5 8
3 6 9
245
Beginner's level
1 4 7
2 5 8
3 6 9
7 4 1
8 5 2
9 6 3
246
Beginner's level
247
Beginner's level
248
Beginner's level
249
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 46
Group Anagrams:
Given an array of strings strs, group
the anagrams together. You can return
the answer in any order.
Input: strs =
["eat”,"tea","tan”,"ate”,"nat","bat"]
Output: [[ "bat"],["nat","tan”],
["ate "eat","tea"]]
Our logic:
to group anagrams together, we can
use a hashmap to store the sorted
version of each word as the key and
the corresponding anagrams as the
value. Here's a JavaScript
implementation of the algorithm:
251
Beginner's level
function groupAnagrams(strs) {
const anagramMap = new Map();
252
Beginner's level
[word]);
}
// Convert the map values to an
array of anagram groups
return
Array.from(anagramMap.values()) ;
253
Beginner's level
254
Beginner's level
255
Beginner's level
256
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 47
Spiral Matrix:
Given an m x n matrix, return all
elements of the matrix in spiral
order.
Our logic:
7o obtain the elements of the matrix
in spiral order, we can use a
simulation approach. We define four
boundaries that represent the 'top',
'bottom', 'left', and 'right' edges
of the matrix, respectively. We start
258
Beginner's level
259
Beginner's level
260
Beginner's level
function spira!Order(matrix) {
if (matrix.length === 0) {
return [];
}
const result = [] ;
let top = 0;
let left = 0;
<•) {
result.push(matrix!top][i]);
}
top++;
261
Beginner's level
+) {
result.push(matrix[i][right]);
}
right--;
// Check if top is still less than
or equal to bottom
if (top <= bottom) {
// Traverse from right to left
for (let i = right; i >= left;
i-) {
result.push(matrix[bottom]
[i]) ;
}
bottom--;
262
Beginner's level
}
left++;
return result;
263
Beginner's level
264
Beginner's level
• transformations.
3. Matrix Operations: Various
mathematical operations on
matrices, such as matrix
multiplication or finding
determinants, require accessing
matrix elements in a specific
order. The spiral matrix algorithm
provides a structured way to access
elements, enabling efficient
computation of matrix operations.
4. Spiral-based Data Representation:
In data visualization or charting
applications, representing data in
a spiral pattern can create
visually appealing and informative
displays. The spiral matrix
algorithm can be used to arrange
and access data points in a spiral
order, facilitating the creation of
engaging visualizations.
5. Grid-based Games or Simulations:
Many games or simulations involve
grid-based environments, where
characters or objects move or
interact with the grid. Traversing
265
Beginner's level
266
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 48
Add Binary:
Given two binary strings a and b,
return their sum as a binary string.
Example 1:
Example 2:
Our logic:
To add two binary strings 'a' and
'b', you can follow these steps:
268
Beginner's level
269
Beginner's level
function addBinary(a, b) {
let result = '';
let carry = 0;
let i = a.length - 1 ;
let j = b.length - 1 ;
parselnt(a[i]) : 0;
const bitB = j >= 0 ?
parselnt(b[j]) : 0;
270
Beginner's level
2).toString(2);
carry = Math.floor(sum / 2);
i--;
j —;
if (carry > 0) {
result = carry + result;
return result;
271
Beginner's level
272
Beginner's level
273
Beginner's level
274
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 49
Climbing Stairs:
You are climbing a staircase. It
takes n steps to reach the top.
Each time you can either climb 1 or 2
steps. In how many distinct ways can
you climb to the top?
Example:
Input: n = 2
Output: 2
Explanation: There are two ways to
climb to the top.
1 . 1 step + 1 step
2 . 2 steps
Our logic:
This problem can be solved using
dynamic programming. We can observe
that the number of distinct ways to
reach step 'n' is equal to the sum of
the distinct ways to reach step 'n-V
and step 'n-2'. This is because we
276
Beginner's level
function climbStairs(n) {
if (n < = 2) {
return n;
}
const dp = [0, 1, 2];
return dp[n];
277
Beginner's level
// Example usage
const n = 5;
const distinctWays = climbStairs(n) ;
console.log(distinctWays); // Output:
8
278
Beginner's level
279
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 50
Same Tree:
Given the roots of two binary trees p
and q, write a function to check if
they are the same or not.
Two binary trees are considered the
same if they are structurally
identical, and the nodes have the
same value.
Example 1:
281
Beginner's level
Example 2:
Our logic:
To check if two binary trees are the
same, we need to compare their
structure and the values of their
nodes.
282
Beginner's level
function isSameTree((p, q) {
// Base case: if both trees are
empty, they are the same
return true;
if (!P II !q) {
return false;
return false;
283
Beginner's level
const isLeftSame =
isSameTree(p.left, q.left);
const isRightSame =
isSameTree(p.right, q.right);
284
Beginner's level
285
Beginner's level
2. Decision-Making Algorithms: In
decision-making processes, binary
trees are often used to represent
decision trees or game trees. By
checking if two decision trees are
the same, decision-makers can
determine if they represent the
same set of decisions or
strategies, enabling them to make
informed choices based on existing
knowledge.
3. Tree-Based Data Structures: The
algorithm is crucial in various
tree-based data structures like
binary search trees, AVL trees, or
red-black trees. It allows
developers to compare and identify
if two trees have the same
structure and values, ensuring the
integrity and consistency of these
data structures.
4. Software Development: Binary trees
are utilized in algorithms for
parsing expressions, generating
code, or optimizing computations.
Checking if two trees are the same
286
Beginner's level
287
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 51
Decode Ways:
A message containing letters from A-Z
can be encoded into numbers using the
following mapping:
289
Beginner's level
Example 1:
Input: s = "12"
Output: 2
Explanation: "12 could be decoded as
"AB‘ (1 2) or "L" (12).
Example 2:
Input: s = "06"
Output: 0
Explanation: "06" cannot be mapped to
"F" because of the leading zero ("6"
is different from "06").
Our logic:
The task is to determine the number
of ways the encoded message can be
decoded.
290
Beginner's level
291
Beginner's level
string.
function numDecodings(s) {
if (S[0] === -0-) {
return 0;
const dp = Array(s.length +
1).fill(0);
dp [ 0 ] = 1 ;
dp [ 1 ] = 1;
for (let i = 2; i <= s.length; i++)
{
const currentDigit = s[i - 1 ];
const prevDigit = s[i - 2];
292
Beginner's level
dp[i] += dp[i - 1 ];
}
if (prevDigit === ’ 1 ' ||
(prevDigit === 2 && currentDigit >=
'0' && currentDigit <= '6')) {
dp[x] += dp[i - 2];
}
}
return dp[s.length];
293
Beginner's level
294
Beginner's level
295
Beginner's level
296
Fi Edi Select Vie
i-n — n dsa.js x
Beginner's level
DSA Challenge 52
Word Search:
Given an 'm x n' grid of characters
board and a string 'word', return
'true' if 'word' exists in the grid.
The word can be constructed from
letters of sequentially adjacent
cells, where adjacent cells are
horizontally or vertically
neighboring. The same letter cell may
not be used more than once.
298
Beginner's level
Our logic:
Here's an algorithm in JavaScript to
solve the problem:
299
Beginner's level
word
if (
row < 0 | |
row >= rows ||
col < 0 ||
) {
return false; // Out of bounds
or mismatching character
380
Beginner's level
301
Beginner's level
+) {
for (let col = 0; col < cols;
CO1++) {
302
Beginner's level
303
Beginner's level
304
Beginner's level
305
Fi Edi Select Vie
i-n — n dsa.js x
Get ready to embark on an
exciting journey into the
depths of Data Structures and
Algorithms!4?
Data Structures &
Algorithms
• for all programmers •
ADVANCED LEVEL
Advanced level
DSA Challenge 1
Example:
3 comb 5 is:
0 1 2, 0 1 3, 0 1 4, 0 2 3, 0 2 4,
0 3 4, 1 2 3, 1 2 4, 1 3 4, 2 3 4
Our logic:
Here's a JavaScript function that
implements this algorithm:
function generateCombinations(m, n) {
const combinations = [];
function backtrack(start, current)
{
if (current.length = = = m) {
combinations.push(current.slice());
308
Advanced level
backtrack(0, [ ]) ;
return combinations;
}
generateCombinations(3, 5);
309
Advanced level
310
Advanced level
311
Advanced level
312
Advanced level
313
Advanced level
DSA Challenge 2
Amicable Pairs:
FreeCell, a solitaire card game, was
introduced by Paul Alfille in 1978 on
the PLATO system. Jim Horne, from
Microsoft, renamed it FreeCell and
developed versions for DOS and
Windows. This release included 32,000
numbered deals. Jim Horne shared the
algorithm as FreeCell gained
popularity, leading to its
replication in other implementations.
The deals range from 1 to 32,000,
while newer Microsoft versions
expanded to 1 million (1 to
1,000,000). Some implementations even
support deal numbers beyond this
range.
315
Advanced level
316
Advanced level
317
Advanced level
318
Advanced level
319
Advanced level
DSA Challenge 3
Deepcopy:
Write a function that returns a deep
copy of a given object. The copy must
not be the same object that was
given.
This task will not test for:
• Objects with properties that are
functions
• Date objects or object with
properties that are Date objects
• RegEx or object with properties
that are RegEx objects
• Prototype copying
Our logic:
function deepCopy(obj) {
let copy = Ar ray.isArray(obj) ? []
: {};
for (let key in obj) {
if (typeof obj[key] === "object"
&& obj[key] !== null) {
copy[key] =
deepCopy(obj[key]);
} else {
321
Advanced level
copy[key] = obj[key];
}
return copy;
}
322
Advanced level
323
Advanced level
324
Advanced level
DSA Challenge 4
Bracket Combinations:
Have the function
BracketCombinations(num) read num
which will be an integer greater than
or equal to zero, and return the
number of valid combinations that can
be formed with num pairs of
parentheses. For example, if the
input is 3, then the possible
combinations of 3 pairs of
parenthesis, namely: ()()(), are ()()
(), ()(()). (())(). ((())). and (()
()). There are □ total combinations
when the input is 3, so your program
should return 5.
Our logic:
To solve this problem, we can use a
recursive approach to generate all
possible combinations of parentheses
and count only the valid ones.
Here's the code for the
Bracketcombinations function:
326
Advanced level
function BracketCombinations(num) {
function
generatecombinations(numOpen,
numClose) {
if (numOpen === 0 && numClose ===
0) {
return 1; // base case: valid
combination found
}
let count = 0;
if (numOpen > 0) {
count +=
generateCombinations(numOpen - 1,
numClose + 1);
}
if (numClose > 0) {
count +=
generateCombinations(numOpen,
numClose - 1);
}
return count;
}
327
Advanced level
328
Advanced level
329
Advanced level
330
Advanced level
DSA Challenge 5
Our logic:
function minJumps(arr) {
// Get the length of the array
let n = arr.length;
332
Advanced level
maxReach = Math,max(maxReach, i +
arr[i]);
step--;
if (step == 0) {
jump++;
if (i >= maxReach) {
return -1;
}
step = maxReach - i;
}
}
return -1;
}
333
Advanced level
334
Advanced level
335
Advanced level
336
Advanced level
337
Advanced level
DSA Challenge 6
Your Task:
You don't need to read input or print
anything. Your task is to complete
the function isBST() which takes the
root of the tree as a parameter and
returns true if the given binary tree
is BST, else returns false.
339
Advanced level
Out logic:
class Solution {
//Function to check whether a Binary
Tree is BST or not.
isBST(root) {
//helper function to check if a
subtree is a valid BST
const isValidBST = (node, minVal,
maxVal) => {
//base case: empty tree is a
valid BST
if (!node) {
return true;
}
if (node.data <= minVal ||
node.data >= maxVal) {
return false;
340
Advanced level
maxVal);
};
//call helper function on root
node
}
}
341
Advanced level
342
Advanced level
343
Advanced level
344
Advanced level
DSA Challenge 7
\
3
/ \ / \
4 5 6 7
\
8
346
Advanced level
Our logic:
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
class Solution {
leftView(root) {
const result = [ ] ;
if (!root) {
return result;
}
const queue = [root];
while (queue.length > 0) {
347
Advanced level
if (node.left) {
queue.push(node.left);
if (node.right) {
queue.push(node.right) ;
}
}
}
348
Advanced level
return result;
349
Advanced level
350
Advanced level
351
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 8
Our logic:
class Node {
constructor(data) {
this.data = data;
this.next = null;
353
Advanced level
class Solution {
// Function to remove a loop in the
linked list.
removeLoop(head) {
if (’head || Shead.next) {
// No loop present in the linked
list.
return;
}
let slow = head;
let fast = head;
354
Advanced level
}
let temp = fast;
while (temp.next !== fast) {
temp = temp.next;
}
temp.next = null;
return;
}
}
}
355
Advanced level
356
Advanced level
357
Advanced level
358
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 9
Your Task:
The task is to write a function
'detectloop()' which contains
reference to the 'head' as only
argument. This function should return
true if linked list contains loop,
else return false.
Our logic:
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
360
Advanced level
class Solution {
}
let slow = head;
let fast = head.next;
while (fast && fast.next) {
if (slow === fast) {
return true;
slow = slow.next;
fast = fast.next.next;
361
Advanced level
return false;
}
}
362
Advanced level
363
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 10
365
Advanced level
Our logic:
let dp = Array(n + 1)
if (wt[i - 1] <= w) {
dp[i][w] = Math.max(val[i - 1]
+ dp[i - 1][w - wt[i - 1]], dp[i - 1]
[w]);
} else {
366
Advanced level
}
return dp[n][W];
367
Advanced level
368
Advanced level
369
Advanced level
• produce.
3. Portfolio optimization: In finance,
the algorithm can be used to
optimize investment portfolios by
selecting the most profitable
assets to invest in given limited
funds.
4. Supply chain management: The
algorithm can be used to optimize
the distribution of goods in supply
chains by selecting the optimal
products to transport given limited
capacity and demand.
370
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 11
Our logic!
function isMatch(s, p) {
// Create a 2D array and initialize
it with false
let dp = Array.from({ length:
s.length + 1 }, () => Array(p.length +
1).fill(false));
372
Advanced level
dp[0][0] = true;
// Handling patterns with at the
start
for (let i - 1; i <= p.length; i++)
{
if (p.charAt(i - 1) === '*') {
dp[0][i] = dp[0][i - 2];
}
}
// Iterate over the entire string and
pattern
for (let i = 1; i <= s.length; i++)
373
Advanced level
{
dp[i][j] = dp[i - 1 ][j - 1 ] ;
}
// If the pattern has a 1 *'
else if (p.charAt(j - 1) ===
’*') {
// Check if the pattern before
the 1 *' matches the current character
374
Advanced level
- 2];
}
else {
dp[i][j] = dp[i][j - 2];
}
}
else {
dp[i][j] = false;
}
// Return the final result
return dp[s.length][p.length];
375
Advanced level
376
Advanced level
377
Advanced level
378
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 12
Our logic:
To solve this problem, we can use a
two-pointer approach. We will
maintain two pointers, 'slow' and
'fast', where 'fast' is 'n' nodes
ahead of 'slow'. Once 'fast' reaches
the end of the list, 'slow' will be
pointing at the node we want to
remove.
380
Advanced level
function removeNthFromEnd(head, n) {
const dummy = new ListNode(0);
dummy.next = head;
let slow = dummy;
let fast = dummy;
}
while (fast.next) {
381
Advanced level
slow = slow.next;
fast = fast.next;
slow.next = slow.next.next;
return dummy.next;
382
Advanced level
383
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 13
Our logic:
The function 'mergeKLists(lists)'
below uses a priority queue (min-
heap) to merge the lists efficiently.
It takes an array of k linked lists
'lists', each of which is sorted in
ascending order. It then merges all
the linked lists into one sorted
linked list and returns it.
385
Advanced level
function mergeKLists(lists) {
// Remove empty lists from the input
array
lists = lists.filter(list => list !
== null);
// Create a dummy head node and a
tail node
let dummy = new ListNode(-1) ;
let tail = dummy;
386
Advanced level
}
// Merge the lists until the
priority queue is empty
while (!heap.isEmpty()) {
// Remove the minimum element from
the priority queue
let node = heap.pop();
387
Advanced level
}
}
// Return the head of the output
list
return dummy.next;
}
// Definition for singly-linked
list.
function ListNode(val, next) {
this.val = (val === undefined ? 0 :
val);
388
Advanced level
null : next);
}
// MinHeap class for the priority
queue
class MinHeap {
constructor() {
this.heap = [];
}
push(node) {
if (node !== null) {
this.heap.push(node) ;
this . heapifyllp( this . heap. length
- 1):
}
}
389
Advanced level
pop() {
if (this.heap.length === 0) {
return null;
}
let min = this.heap[0] ;
let last = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = last;
this.heapifyDown(0) ;
}
return min;
heapifyllp(i) {
while (i > 0) {
let j = Math.floor((i - 1) / 2);
390
Advanced level
if (this.heapfi].val <
this.heap[j].val) {
[this.heap[i], this.heap[j]] =
[this.heap[j], this.heap[i]];
i = j;
} else {
break;
}
}
}
heapifyDown(i) {
while (true) {
let left = 2 * i + 1 ;
let right = 2 * i + 2;
let smallest = i;
391
Advanced level
}
if (right < this.heap.length &&
this.heap[right].val <
this.heap[smallest].val) {
smallest = right;
}
if (smallest !== i) {
[this.heap[i],
this.heap[smallest] ] =
[this.heap[smallest], this.heap[i]] ;
i = smallest;
392
Advanced level
else {
break;
}
}
}
IsEmptyO {
return this.heap.length === 0;
}
}
393
Advanced level
394
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 14
N-Queens:
The n-queens puzzle is the problem of
placing 'n' queens on an 'n x n'
chessboard such that no two queens
attack each other.
396
Advanced level
Example:
Input: n = 4
Output: [[",Q.. ..Q","Q....Q."],
[ ' . .Q. *', "Q. -Q", " .Q. ." ] ]
Explanation: There exist two distinct
solutions to the 4-queens.
Our logic:
Here's a JavaScript program that
solves the n-queens puzzle and
returns all distinct solutions:
function solveNQueens(n) {
const solutions = [ ] ;
const board = Array.from({ length: n
}, () => Array(n).fill('.'));
backtrack(0, board);
function backtrack(row, board) {
if (row === n) {
397
Advanced level
solutions.push(board.map(row =>
row.join('')));
return;
}
for (let col = 0; col < n; col++)
{
if (isValidMove(row, col,
board)) {
board[row][col] = ' Q’ ;
backtrack(row + 1, board);
board[row][col] = * . ' ;
}
}
}
function isValidMove(row, col,
board) {
398
Advanced level
}
const j = row - i;
- j] === 'Q') {
return false;
}
if (col + j < n && board[i][col
+ j] === 'Q') {
return false;
}
}
return true;
399
Advanced level
return solutions;
// Example usage
const n = 4;
const solutions = solveNQueens(n);
console.log(solutions);
400
Advanced level
401
Advanced level
solution. Backtracking is a
fundamental concept used in various
algorithms and real-world scenarios.
3. Constraint Satisfaction Problems:
The N-Queens problem belongs to a
class of problems known as
constraint satisfaction problems
(CSPs). CSPs are prevalent in
fields like artificial
intelligence, operations research,
scheduling, and logistics.
Understanding the N-Queens
algorithm helps in designing and
solving similar CSPs.
4. Parallel Computing: The N-Queens
algorithm can be parallelized to
improve performance by utilizing
multiple processors or cores. This
concept is valuable in high-
performance computing, distributed
systems, and optimizing resource
utilization.
5. Education and Research: The N-
Queens problem serves as an
educational tool to teach and
illustrate various concepts in
402
Advanced level
403
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 15
Permutation Sequence:
Given a set of numbers from 1 to n,
where 'n' is a positive integer, the
set contains n! (n factorial) unique
permutations. By listing and labeling
all the permutations in a specific
order, we obtain a sequence of
permutations. For example, when n =
3', the sequence would be: "123"
132", 213", "231", "312", 321
Example 1:
Input: n = 3, k = 3
Output: "213"
405
Advanced level
Example 2:
Input: n = 4, k = 9
Output: "2314"
Example 3:
Input: n = 3, k = 1
Output: "123"
function getPermutation(n, k) {
const nums = Array.from({ length: n
406
Advanced level
factorial) - 1;
result += nums[index];
nums.splice(index, 1);
k = k % factorial;
n--;
}
return result;
}
function getFactorial(num) {
let factorial = 1;
for (let i = 2; i <= num; i++) {
factorial *= i;
}
return factorial;
407
Advanced level
// Example usage:
console.log(getPermutation(3, 3));
// Output: "213"
408
Advanced level
1. Combinatorial Optimization:
Permutation algorithms are used in
409
Advanced level
410
Advanced level
411
Advanced level
DSA Challenge 16
Text Justification:
Given an array of strings 'words and
a width 'maxWidth', write a program
that will format the text such that
each line has exactly 'maxWidth'
characters and is fully (left and
right) justified.
413
Advanced level
Note:
• A word is defined as a character
sequence consisting of non-space
characters only.
• Each word's length is guaranteed to
be greater than 0' and not exceed
'maxWidth'.
• The input array words' contains at
least one word.
Example:
414
Advanced level
Our logic:
Here's a JavaScript program that
formats the text according to the
given requirements:
{
const lines - [];
let currentLine = [];
let currentwidth = 0;
for (let i = 0; i < words.length; i+
+) {
const word = words[i];
if (currentwidth +
currentLine.length + word.length <=
maxWidth) {
currentLine.push(word);
currentwidth += word.length;
415
Advanced level
} else {
lines.push(j ustifyLine(currentLine,
currentwidth, maxWidth));
currentLine = [word];
currentwidth = word.length;
}
lines.push(j ustifyLastLine(currentLi
ne, currentwidth, maxWidth));
return lines;
function j ustifyLine(line,
currentwidth, maxWidth) {
const numWords = line.length;
const numSpaces = maxWidth -
currentwidth;
if (numWords === 1) {
416
Advanced level
return line[0] + *
' .repeat(numSpaces);
}
const numGaps = numWords - 1 ;
const spacesPerGap =
Math.floor(numSpaces / numGaps);
const extraSpaces = numSpaces %
numGaps;
let justifiedLine = '1;
for (let i = 0; i < numWords; i++) {
justifiedLine += line[i];
if (i < numGaps) {
justifiedLine += 1
' .repeat(spacesPerGap);
if (i < extraSpaces) {
justifiedLine += ' ' ;
417
Advanced level
}
}
}
return j ustifiedLine;
function justifyLastLine(line,
currentwidth, maxWidth) {
let justifiedLine = line.join(' ');
const numSpaces = maxWidth -
currentwidth - (line.length - 1);
justifiedLine += '
' . repeat(numSpaces);
return justifiedLine;
418
Advanced level
419
Advanced level
420
Advanced level
421
Advanced level
DSA Challenge 17
Partition List:
Given the head of a linked list and a
value 'x', partition it such that all
nodes less than x' come before nodes
greater than or equal to x'.
Example:
423
Advanced level
Our logic:
To solve this problem, we can use a
two-pointer approach. We maintain two
separate lists: one for nodes less
than x and another for nodes greater
than or equal to x. We iterate
through the original linked list and
append nodes to their respective
lists based on the given condition.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
>
function partition(head, x) {
// Create two dummy nodes for the
two partitions
424
Advanced level
while (head) {
if (head.val < x) {
// Node less than x, append to
before partition
before.next = head;
before = before.next;
} else {
// Node greater than or equal to
x, append to after partition
after.next = head;
after = after.next;
425
Advanced level
}
// Connect the two partitions and
set the last node's next as null
after.next = null;
iefore.next = afterHead.next;
426
Advanced level
427
Advanced level
428
Advanced level
429
Advanced level
DSA Challenge 18
Restore IP Addresses:
A valid IP address consists of
exactly four integers separated by
single dots. Each integer is between
'0' and '255' (inclusive) and cannot
have leading zeros.
• For example, ”0.1.2.201" and
"192.168.1.1" are valid IP
addresses, but "0.011.255.245",
"192.168.1.312" and "[email protected]"
are invalid IP addresses.
Example:
Input: s = "25525511135"
Output:
["255.255.11.135","255.255.111 .35"]
431
Advanced level
Our logic:
To solve the problem of generating
valid IP addresses from a given
string, we can use a recursive
approach.
function restorelpAddresses(s) {
const result = [];
backtraces, [], result);
return result;
>
function backtrack(remaining,
ipAddress, result) {
if (ipAddress.length === 4 &&
remaining === '') {
result.push(ipAddress.join(1 . ' )) ;
return;
432
Advanced level
}
if (ipAddress.length === 4 ||
remaining === '') {
return;
}
for (let i = 1; i <= 3 && i <=
remaining.length; i++) {
const segment = remaining.slice(0,
i);
if (isValidSegment(segment)) {
ipAddress.push(segment);
backtrack(remaining.slice(i),
ipAddress, result);
ipAddress.pop() ;
}
}
433
Advanced level
function IsValidSegment(segment) {
if (segment.length > 1 && segment[0]
=== '0') {
return false;
}
const num = parselnt(segment);
return num >= 0 && num <= 255;
// Example usage:
console.log(restorelpAddresses("255255
11135'));
434
Advanced level
435
Advanced level
436
Advanced level
437
Advanced level
DSA Challenge 19
Example 1:
Input: n = 3
Output: 5
Example 2:
Input: n = 1
Output: 1
439
Advanced level
Our logic:
Here's a JavaScript program that
calculates the number of structurally
unique BSTs for a given integer n:
function countllniqueBSTs(n) {
const dp = new Array(n +
dp[0] = 1;
dp[1] = 1;
return dp[n];
440
Advanced level
// Example usage:
console.log(countUniqueBSTs(3)); //
Output: 5
441
Advanced level
442
Advanced level
443
Advanced level
DSA Challenge 20
Example:
445
Advanced level
Our logic:
To determine if a binary tree is a
valid binary search tree (BST), you
can use the following algorithm:
1 . Implement a recursive helper
function that takes a node, along
with a minimum and maximum value.
2. If the current node is null, return
true since an empty tree is
considered a valid BST.
3. If the current node's value is not
within the valid range defined by
the minimum and maximum, return
false.
4. Recursively call the helper
function for the left subtree,
passing the updated maximum value
as the new maximum.
5. Recursively call the helper
function for the right subtree,
passing the updated minimum value
as the new minimum.
6. If both recursive calls return
true, it means the left and right
subtrees are valid BSTs, so return
true.
446
Advanced level
function isValidBST(root) {
return isValidBSTHelper(root, null,
null) ;
}
function isValidBSTHelper(node, min,
max) {
if (node === null) {
return true;
}
if ((min !== null && node.val <=
min) || (max !== null && node.val >=
max)) {
return false;
447
Advanced level
}
return (
isValidBSTHelper(node.left, min,
node.val) &&
isValidBSTHelper(node.right,
node.val, max)
);
448
Advanced level
449
Advanced level
450
Advanced level
DSA Challenge 21
Example:
452
Advanced level
Our logic:
To recover a binary search tree (BST)
where the values of exactly two nodes
were swapped, you can use the
following JavaScript program:
class TreeNode {
constructor(val, left, right) {
this.val = val;
function recoverTree(root) {
let firstNode = null;
let secondNode = null;
let prevNode = new TreeNode(-
Infinity);
453
Advanced level
}
if (firstNode && prevNode.val >=
node.val) {
secondNode = node;
}
prevNode = node;
454
Advanced level
findSwappedNodes(node.right);
}
// Find the two swapped nodes in the
BST
findSwappedNodes(root);
// Swap the values of the two nodes
const temp = firstNode.val;
firstNode.val = secondNode.val;
secondNode.val = temp;
return root;
455
Advanced level
structure.
456
Advanced level
457
Advanced level
458
Fi Edi Select Vie
|-Pl ”• HDSA.js X
Advanced level
DSA Challenge 22
Example 1:
Example 2:
Input: root =
Output: [[1]]
460
Advanced level
Our logic:
Here's a JavaScript program that
performs a level order traversal on a
binary tree and returns the nodes'
values in an array:
class TreeNode {
constructor(val, left = null, right
= null) {
this.val = val;
this.left = left;
this.right = right;
function levelOrderTraversal(root) {
if (!root) {
return [ ];
461
Advanced level
+) {
const node = queue.shift();
currentLevel.push(node.val);
if (node.left) {
queue.push(node.left) ;
}
if (node.right) {
queue.push(node.right) ;
}
}
result.push(currentLevel) ;
462
Advanced level
return result;
}
// Example usage:
const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
console.loc(levelOrderT raversal(root
)); // Output: [[3], [9, 20], [15, 7]]
463
Advanced level
464
Advanced level
465
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 23
Example:
467
Advanced level
Our logic:
Here's a JavaScript program that
performs the zigzag level order
traversal of a binary tree:
class TreeNode {
constructor(val, left = null, right
= null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function zigzagLevelOrder(root) {
if (!root) return [];
const result = [];
const queue = [root];
let level = 0;
while (queue.length > 0) {
468
Advanced level
+) {
const node = queue.shift() ;
if (level % 2 === 0) {
levelNodes.push(node.val); //
Left to right
} else {
levelNodes.unshift(node.val) ;
// Right to left
}
if (node.left)
queue.push(node.left) ;
if (node.right)
queue.push(node.right) ;
469
Advanced level
result.push(levelNodes);
level++;
}
return result;
I
// Example usage:
const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
console.log(zigzagLevelOrder(root));
// Output: [[3], [20, 9], [15, 7]]
470
Advanced level
471
Advanced level
472
Advanced level
473
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 24
Example:
475
Advanced level
Our logic:
Here's a JavaScript program to
construct a binary tree from its
preorder and inorder traversals:
class TreeNode {
constructor(val, left = null, right
= null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function buildTree(preorder, inorder)
{
if (preorder.length === 0 ||
inorder.length === 0) {
return null; // Base case: empty
arrays
476
Advanced level
}
const rootVal = preorder[0];
const root = new TreeNode(rootVal);
const rootindex =
inorder.indexOf(rootVal);
const leftinorder = inorder.slice(0,
rootindex);
const rightinorder =
inorder.slice(rootindex + 1);
const leftPreorder =
preorder.slice(1, 1 +
leftinorder.length) ;
const rightPreorder =
preorder.slice(1 +
leftInorder.length);
root.left = buildTree(leftPreorder,
477
Advanced level
leftinorder);
root.right =
buildT ree(rightPreorder,
rightinorder);
return root;
// Example usage:
const preorder = [3, 9, 20, 15, 7];
const inorder = [9, 3, 15, 20, 7];
const root = buildTree(preorder,
inorder);
console.log(root);
478
Advanced level
479
Advanced level
480
Advanced level
481
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 25
Example:
483
Advanced level
Our logic:
Here's a JavaScript program to
construct a binary tree from its
preorder and inorder traversals:
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
class TreeNode {
constructor(val, left = null, right
= null) {
484
Advanced level
this.val = val;
this.left = left;
this.right = right;
}
>
function sortedListToBST(head) {
if (!head) {
return null;
}
// Find the middle node of the
linked list
const midNode = findMiddle(head);
// Create a new TreeNode with the
middle value
const rootNode = new
TreeNode(midNode.val);
485
Advanced level
}
// Recursively convert the left and
right halves of the linked list to BST
rootNode.left =
sortedListToBST(head) ;
rootNode.right =
sortedListToBST(midNode.next);
return rootNode;
function findMiddle(head) {
let slow = head;
let fast = head;
let prev = null;
486
Advanced level
}
if (prev) {
prev.next = null; // Break the
linked list into two halves
}
return slow;
}
// Example usage:
const linkedList = new ListNode(-10);
linkedList.next = new ListNode(-3);
linkedList.next.next = new
ListNode(0);
linkedList.next.next.next - new
487
Advanced level
ListNode(5) ;
linkedList.next.next.next.next = new
ListNode(9);
const bst =
sortedListToBST(linkedList);
console.log(bst);
488
Advanced level
489
Advanced level
490
Advanced level
491
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 26
Example:
493
Advanced level
Our logic:
Here's a JavaScript program that
flattens a binary tree into a linked
list using a pre-order traversal:
class TreeNode {
this.val = val;
this.left = left;
this.right = right;
function flattenTree(root) {
494
Advanced level
if (!root) return ;
let stack = [root];
let prev = null;
while (stack.length) {
let node = stack.pop();
if (node.right) {
stack.push(node.right);
}
if (node.left) {
stack.push(node.left);
}
if (prev) {
prev.right = node;
prev.left = null;
}
prev = node;
495
Advanced level
497
Advanced level
498
Advanced level
• data structures.
4. Integration with Other Data
Structures: The flattened linked
list can be seamlessly integrated
with other data structures or
algorithms that expect linear
structures. This enables efficient
data processing and interoperation
with existing algorithms or systems
that operate on sequential data.
499
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 27
Distinct Subsequences:
Given two strings 's' and 't'( return
the number of distinct
subsequences (i.e. a string that is
derived from another string by
deleting some or no characters
without changing the order of the
remaining characters) of 's' which
equals 't'.
Example:
501
Advanced level
Our logic:
Here's a JavaScript program that
calculates the number of distinct
subsequences of s' that equal 't':
function numDistinct(s, t) {
const m = s.length;
const n = t.length;
// Create a 2D array to store the
dynamic programming results
const dp = Array(m +
1).fill(O).map(() => Array(n +
1).fill(0));
// Initialize the first column with
1s since an empty string is a
subsequence of any string
for (let i = 0; i <= m; i++) {
dp[i][0] = 1 ;
502
Advanced level
dp[i - 1][j];
} else {
// If the characters don't
match, we can only exclude the current
character
dp[i][j ] = dp[i - 1 ] [ j ];
}
}
503
Advanced level
}
return dp[m][n];
}
// Example usage:
console.log(numDistinct("babgbag",
"bag")); // Output: 5
504
Advanced level
505
Advanced level
506
Advanced level
507
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 28
T rianqle:
Given a 'triangle' array, return the
minimum path sum from top to bottom.
Example:
509
Advanced level
Our logic:
Here's a JavaScript program that
calculates the minimum path sum in a
triangle array:
function minimumTotal(triangle) {
11 [i];
510
Advanced level
{
for (let j = 0; j <= i; j++) {
// Choose the smaller of the two
adjacent numbers below and add it to
the current number
dp[i][j] = Math.min(dp[i + 1]
[j], dp[i + 1](j + 1]) + triangle[i]
[ i ];
}
// The minimum path sum will be
stored at the top of the dp array
return dp[0][0];
511
Advanced level
// Example usage:
const triangle = [
[2],
[3, 4],
[6, 5, 7],
[4, 1, 8, 3]
];
console.log(minimumTotal(triangle));
// Output: 11
512
Advanced level
513
Advanced level
514
Advanced level
515
Advanced level
DSA Challenge 29
Example 1:
517
Advanced level
Example 2:
Example 3:
518
Advanced level
Our logic:
Here's a JavaScript program that that
considers all possible transactions:
function maxProfit(prices) {
let maxProfit = 0;
for (let i = 1; i < prices.length;
i++) {
// Add the difference between
current and previous price if it's
positive
if (prices[i] > prices[i - 1]) {
maxProfit +- prices[i] -
prices[i - 1];
}
}
return maxProfit;
519
Advanced level
// Example usage:
const prices = [7, 1, 5( 3, 6, 4];
console.log(maxProfit(prices)) ; //
Output: 7
At each iteration:
• It checks if the current price is
lower than the minPrice' and
updates it if necessary.
• Then it calculates the potential
profit by subtracting the
'minPrice' from the current price.
• It updates the 'maxProfit' if a
higher profit is found.
520
Advanced level
521
Advanced level
• trading decisions.
2. Portfolio Management: Portfolio
managers utilize the algorithm to
optimize their investment
portfolios. By identifying the best
times to buy and sell stocks, they
can rebalance their portfolios and
allocate their resources
effectively to achieve higher
returns.
3. Algorithmic Trading: The algorithm
is widely used in algorithmic
trading systems, where automated
programs execute trades based on
predefined strategies. It enables
the systems to make real-time
buying and selling decisions,
improving trading efficiency and
profitability.
4. Risk Management: The algorithm aids
in risk management by helping
investors and traders identify
potential losses and take
preventive measures. By considering
the best time to exit a position,
it minimizes the risk of holding
522
Advanced level
523
Advanced level
DSA Challenge 30
Example 1:
525
Advanced level
Example 2:
Example 3:
526
Advanced level
Our logic:
Here's a JavaScript program that
solves the problem:
function maxProfit(prices) {
const n = prices.length;
let buyl = -prices[0]; // maximum
profit after the first buy
let selll = 0; // maximum profit
after the first sell
let buy2 = -prices[0]; // maximum
profit after the second buy
let sell2 =0; // maximum profit
after the second sell
527
Advanced level
}
return sell2;
// Example usage:
const prices = [3, 3, 5, 0, 0, 3, 1,
4];
const maxProfitValue =
maxProfit(prices) ;
console.log(maxProfitValue);
528
Advanced level
529
Advanced level
530
Advanced level
531
Advanced level
DSA Challenge 31
Word Ladder:
Given two words, 'beginWord' and
'endWord', and a dictionary
'wordList', return the number of
words in the shortest transformation
sequence from ‘beginWord* to
'endWord*, or *0' if no such sequence
exists.
Example 1:
533
Advanced level
Example 2:
Our logic:
Here's a JavaScript program that
solves the problem using a breadth-
first search algorithm:
function ladderLength(beginWord,
endWord, wordList) {
const wordSet = new Set(wordList);
if (!wordSet.has(endWord)) {
return 0;
534
Advanced level
i++) {
const wordArray =
word.split('');
for (let j = 97; j <= 122; j++)
{
const char =
String.fromCharCode(j);
535
Advanced level
wordArray[i] = char;
const newWord =
wordArray.join('’ );
if (newWord === endWord) {
return length + 1 ; //
Transformation sequence found
}
if (wordSet.has(newWord) && !
visited.has(newWord)) {
queue.push([newWord, length
+ U);
visited.add(newWord);
536
Advanced level
return 0; // No transformation
sequence found
537
Advanced level
538
Advanced level
539
Advanced level
540
Advanced level
DSA Challenge 32
Example 1:
Example 2:
542
Advanced level
Our loiic:
Here's a JavaScript program that
finds the length of the longest
consecutive elements sequence in an
unsorted array 'nums':
function longestConsecutive(nums) {
if (nums.length === 0) {
return 0;
}
let numSet = new Set(nums);
let longestStreak = 0;
while (numSet.has(currentNum +
1)) {
currentNum++;
543
Advanced level
currentStreak++;
}
longestStreak =
Math.max(longestStreak,
currentstreak);
}
}
return longestStreak;
// Example usage:
let nums = [100, 4, 200, 1, 3, 2];
console.log(longestConsecutive(nuns));
// Output: 4
544
Advanced level
545
Advanced level
546
Advanced level
547
Advanced level
DSA Challenge 33
Surrounded Regions:
Given an 'm x n' matrix board
containing 'X' and 'O', capture all
regions that are 4-directionally
surrounded by 'X1.
Example 1:
Example 2:
X X X X
X o o X
X X o X
X o X X
549
Advanced level
Example 2:
Our logic:
Here's a JavaScript program that
captures the surrounded regions in a
matrix:
550
Advanced level
function solve(board) {
if (board.length === 0) return;
const m = board.length;
const n = board[0].length;
// Define helper function to perform
depth-first search
function dfs(i, j) {
if(i<0||i>=m||j<0||j
>= n || board[i][j] !== '0') return;
board[i][j] = ; // Mark the '0'
as visited
// Explore the four directions
dfs(i - 1, j);
dfs(i + 1, j);
dfs(i, j - 1);
dfs(i, j + 1);
551
Advanced level
}
// Traverse the first and last
columns
for (let i = 0; i < m; i++) {
dfs(i, 0);
dfs(i, n - 1);
}
// Traverse the first and last rows
for (let j =1; j < n - 1; j++) {
dfs(0, j);
dfs(m - 1, j);
}
// Convert remaining 'O' to 'X' and
restore '#' back to 'O'
552
Advanced level
{
boa rd[i] [ j] = 'O';
}
}
}
// Example usage:
const board = [
['X', 'X', 'X', 'X'],
['X', 'O', 'O', 'X'],
['X', 'X', 'O', 'X' ],
553
Advanced level
];
solve(board) ;
console.log(board);
554
Advanced level
555
Advanced level
556
Advanced level
DSA Challenge 34
Palindrome Partitioning:
Given a string 's', partition s
such that every substring of the
partition is a palindrome.
Example 1:
Input: s = "aab
Output: 1
Explanation: The palindrome
partitioning ["aa","b"] could be
produced using 1 cut.
Example 2:
Input: s = "a
Output:0
558
Advanced level
Our logic:
Here's a JavaScript program that
solves the problem using dynamic
programming:
function minCut(s) {
const n = s.length;
const isPalindrome = Array.from({
length: n }, () =>
Array(n).fill(false));
const dp = Array(n).fill(n);
if (j === 0) {
dp[i] = 0;
559
Advanced level
} else {
dp[i] = Math.min(dp[i], dp[j
- 1] + 1);
}
}
}
}
return dp[n - 1 ] ;
// Example usage:
const s = "aab";
const result = minCut(s);
console.log(result); // Output: 1
560
Advanced level
561
Advanced level
562
Advanced level
563
Advanced level
564
Fi Edi Select Vie
|-Pl ”• HDSA.js X
Advanced level
DSA Challenge 35
Gas Station:
There are 'n' gas stations along a
circular route, where the amount of
gas at the 'ith' station is gas[i]‘.
566
Advanced level
Example:
567
Advanced level
Our logic:
Here's a JavaScript program that
solves the problem:
{
const n = gas.length;
let totalGas = 0;
let currentGas = 0;
let startstation = 0;
for (let i = 0; i < n; i++) {
totalGas += gas[i] - cost[i];
currentGas += gas[i] - cost[i];
if (currentGas < 0) {
// Cannot reach the next
station, reset the start station
startstation = i + 1 ;
currentGas = 0;
568
Advanced level
}
}
: -i;
}
569
Advanced level
570
Advanced level
571
Advanced level
572
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 36
Candy:
There are 'n' children standing in a
line. Each child is assigned a rating
value given in the integer array
'ratings'.
574
Advanced level
Example 1:
Example 2:
575
Advanced level
Our logic:
Here's a JavaScript program that
solves the problem:
function candy(ratings) {
const n = ratings.length;
const candies = new
Array(n).fill(1); // Initialize
candies array with minimum values
// Traverse from left to right, and
assign more candies to the right
neighbor if their rating is higher
for (let i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
576
Advanced level
i);
}
}
// Calculate the total number of
candies
let totalCandies = 0;
for (let i = 0; i < n; i++) {
totalCandies += candies[i];
577
Advanced level
}
return totalCandies;
// Example usage:
const ratings = [1, 2, 3, 2, 1];
console.log(candy(ratings)) ; //
Output: 9
578
Advanced level
579
Advanced level
• of items to be recommended to
users.
3. Resource Allocation: The algorithm
can be used in resource allocation
problems, where resources need to
be distributed among different
entities based on their
requirements or priorities. For
example, in project management, it
can help allocate resources to
tasks or team members based on
their complexity or importance.
4. Fair Distribution: The algorithm
can be applied in situations where
resources or rewards need to be
distributed among individuals in a
fair and equitable manner. By
considering the ratings or
preferences of individuals, it
ensures that the distribution is
proportional to their merit or
contribution.
580
Advanced level
581
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 37
Word Break:
Given a string s' and a dictionary
of strings 'wordDict', add spaces in
s to construct a sentence where each
word is a valid dictionary word.
Return all such possible sentences in
any order.
Example 1:
583
Advanced level
Example 2:
Example 3:
Input: s = "pineapplepenapple",
wordDict =
["apple","pen","applepen","pine","pinea
pple"]
Output: s = "pineapplepenapple ,
wordDict =
["apple", ' pen", 'applepen , pine", pinea
pple”]
Explanation: Note that you are allowed
to reuse a dictionary word.
584
Advanced level
Our logic:
Here's a JavaScript program that
solves the given problem:
}
const result = [ ] ;
if (wordSet.has(s)) {
result.push(s);
}
for (let i = 1; i < s.length; i++)
585
Advanced level
}
}
}
memo.set(s, result);
return result;
586
Advanced level
return backtrack(s);
}
// Example usage:
const s = "catsanddog ';
const wordDict = ["cat", "cats",
"and", "sand”, "dog”];
const sentences = wordBreak(s,
wordDict);
console.log(sentences);
587
Advanced level
588
Advanced level
589
Advanced level
590
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 38
Example 1:
592
Advanced level
Example 2:
5
4
3
2-
593
Advanced level
Our logic:
To solve the problem of finding the
maximum number of points that lie on
the same straight line, you can use
the following JavaScript program:
function maxPoints(points) {
if (points.length <= 2) {
return points.length;
}
let maxCount = 0;
for (let i = 0; i < points.length;
i++) {
const slopes = new Map();
let samePointCount = 1 ;
let currMax = 0;
for (let j = i + 1; j <
points.length; j++) {
594
Advanced level
points[i][0];
const yDiff = points!j][1] -
points[i][1];
if (xDiff === 0 && yDiff === 0)
{
samePointCount++;
continue;
let slope;
if (xDiff === 0) {
slope = Infinity;
} else {
slope = yDiff / xDiff;
595
Advanced level
slopes.set(slope, (slopes.get(slope)
Il 0) + i);
currMax = Math.max(currMax,
slopes.get(slope));
}
maxCount = Math.max(maxCount,
currMax + samePointCount);
}
return maxCount;
596
Advanced level
597
Advanced level
598
Advanced level
599
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 39
Maximum Gap:
Given an integer array 'nums', return
the maximum difference between two
successive elements in its sorted
form. If the array contains less than
two elements, return '0'.
Example 1:
Example 2:
601
Advanced level
Our logic:
Here's a JavaScript program that
solves the problem using the bucket
sort algorithm:
function maximumDifference(nums) {
const n = nums.length;
if (n < 2) return 0;
let minVal = Infinity;
let maxVal = -Infinity;
// Find the minimum and maximum
values in the array
for (let num of nums) {
minVal = Math.min(minVal, num);
maxVal = Math.max(maxVal, num);
}
// Calculate the interval size
const interval = Math.ceil((maxVal -
602
Advanced level
minVal) / (n - 1)) ;
// Create n-1 buckets to store the
minimum and maximum values
const minBucket = new Array(n -
1).fill(Infinity);
const maxBucket = new Array(n -
1).fill(-Infinity);
// Distribute elements into the
buckets
for (let num of nums) {
if (num === minVal || num ===
maxVal) continue;
const index = Math.floor((num -
minVal) / interval);
minBucket[index] =
Math.min(minBucket[index], num);
603
Advanced level
maxBucket[index] =
Math.max(maxBucket[index], num) ;
604
Advanced level
}
// Example usage:
const nums = [3, 6, 9, 1];
console.log(maximumDifference(nums));
// Output: 3
605
Advanced level
606
Advanced level
607
Fi Edi Select Vie
i-n — n dsa.js x
Advanced level
DSA Challenge 40
Example 1:
Input: s = 11AAAAAAAAAAAAA"
Output: ["AAAAAAAAAA"]
609
Advanced level
Example 2:
Input: s =
"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
Output: ["AAAAACCCCC","CCCCCAAAAA"]
Our logic:
Here's a JavaScript program that
returns all the 10-letter-long
sequences that occur more than once
in a given DNA sequence:
function findRepeatedSequences(s) {
const sequenceMap = new Map();
const result = [ ] ;
i++) {
const sequence = s.substring(i, i
+ 10);
610
Advanced level
sequenceMap.set(sequence,
(sequenceMap.get(sequence) || 0) + 1);
if (sequenceMap.get(sequence) ===
2) {
result.push(sequence);
}
}
return result;
// Example usage:
const dnaSequence = "ACGAATTCCG";
const repeatedSequences =
findRepeatedSequences(dnaSequence);
console.log(repeatedSequences);
611
Advanced level
612
Advanced level
613
Advanced level
614
Advanced level
615
Advanced level
DSA Challenge 41
House Robber:
You are a professional robber
planning to rob houses along a
street. Each house has a certain
amount of money stashed, the only
constraint stopping you from robbing
each of them is that adjacent houses
have security systems connected and
it will automatically contact the
police if two adjacent houses were
broken into on the same night.
Example 1:
617
Advanced level
Example 2:
Our logic:
To solve the problem of robbing
houses without alerting the police
and maximizing the stolen money, you
can use a dynamic programming
approach. Here s a JavaScript program
that implements the solution:
function rob(nums) {
const n = nums.length;
if (n === 0) return 0;
618
Advanced level
619
Advanced level
}
return dp[n-1 ];
620
Advanced level
621
Advanced level
622
Advanced level
DSA Challenge 42
Dungeon Game:
The demons had captured the princess
and imprisoned her in the bottom
right corner of a dungeon'. The
'dungeon' consists of 'm x n' rooms
laid out in a 2D grid. Our valiant
knight was initially positioned in
the top-left room and must fight his
way through 'dungeon' to rescue the
princess.
624
Advanced level
625
Advanced level
Example 2:
Our logic:
Here's a JavaScript program that
solves the problem:
function calculateMinimumHP(dungeon) {
const m = dungeon.length;
626
Advanced level
const n = dungeon[0].length;
const dp = new Array(m +
1).f111(0).map(() => new Array(n +
1).fill(Infinity));
dp[m][n - 1] = 1 ;
dp[m - 1][n] = 1 ;
[j];
dp[i][j ] = Math.max(1,
minHealth);
}
}
627
Advanced level
return dp[0][0];
}
// Example usage:
const dungeon = [
[-2, -3, 3],
I;
const minlnitialHealth =
calculateMinimumHP(dungeon);
console.log(minlnitialHealth);
628
Advanced level
629
Advanced level
630
Glossary
632
Glossary
633
Glossary
634
Glossary
635
Notes
636