Question 1: Unique element in an array that occurs only once all
others occur twice
https://www.naukri.com/code360/problems/find-unique_625159?
source=youtube&campaign=love_babbar_codestudio1&utm_source=yout
ube&utm_medium=affiliate&utm_campaign=love_babbar_codestudio1
a^a=0
Question 2:
If we xor the given array with array of 1 to N-1 then the duplicate element
occurs thrice and all others occurs twice so only the duplicate element
gets left behind
Problem 3:
Because of the constraints given we can also set the value above 10^5 or
below 0 instead if INT_MIN
Optimisation 1:
Optimisation 2: O(max(M,N))
Problem 4:
Problem 5:
Sorting zeros and ones only
Using 2 pointer approach:
We don’t use static for functions in leetcode
gives no:of digits in decimal
If we use log2 it gives no:of digits in binary
If we give log8 it gives no:of digits in octal
https://www.geeksforgeeks.org/problems/data-type-1666706751/1?
utm_source=youtube&utm_medium=collab_striver_ytdescription&utm_campaign=data-type
In C++ switch cannot be used with strings but in java we can
sizeof operator does not work in Java
In java for List<Double> arr; arr[0] does not work we must use arr.get[0]
Integer.SIZE: This returns the size of the int type in bits. The
constant Integer.SIZE is 32 because an int in Java is 32 bits.
Integer.SIZE / 8: Divides the size in bits by 8 to convert it to bytes.
So, 32 bits / 8 = 4 bytes.
Character Arrays and Strings:
str.equals("Integer") : This checks if the input string is "Integer".--
>JAVA
Searching in a String in JAVA
Using Arrays.toString inside System.out.println is a convenient way to print the contents
of an array in a readable format. The Arrays.toString method converts the array into a string
representation, making it easier to visualize the elements.
Arrays.toString(intArray) converts the integer array intArray into a string
representation [1, 2, 3, 4, 5].
Arrays.toString(stringArray) converts the string array stringArray into a string
representation [apple, banana, cherry].
+ does not work for sb unless one of it is a string
Implicit typecasting from char to int
C++ String Functions:
str.clear(); removes all characters from the string
Question : https://leetcode.com/problems/string-compression/description/
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/description/
Best Solutions:
The below solution is failing for really long strings giving TLE error
2D Arrays
Searching in 2D arrays in Java
Here we use return new int[]{row, col}; because we haven’t declared it unlike below
Binary Search
If target is not found then the answer would be at arr[start] at the last
If we need to find element greatest element smaller than target the answer would be arr[end].
https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/ since wrap
around is involved we should return letters[start]%letters.length
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
Ans:- https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/blob/main/lectures/10-binary
%20search/code/src/com/kunal/FirstAndLastPosition.java
https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/blob/main/lectures/10-binary%20search/
code/src/com/kunal/InfiniteArray.java
https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/blob/main/lectures/10-binary%20search/
code/src/com/kunal/Mountain.java
https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/blob/main/lectures/10-binary%20search/
code/src/com/kunal/SearchInMountain.java
https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/blob/main/lectures/10-binary%20search/
code/src/com/kunal/RBS.java -->Binary Search in Rotated array
https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/blob/main/lectures/10-binary%20search/
code/src/com/kunal/RotationCount.java -->if duplicates exist in Rotated sorted array
https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/blob/main/lectures/10-binary%20search/
code/src/com/kunal/SplitArray.java -->split array largest sum
Binary Search in 2D arrays
If we go through each row and compare with first and last element of that row and then perform a
binary search the time complexity would be O(n)+O(log2m) since after going through each row we
only perform binary search on one row not on all rows.
If we hypothetically flatten it then complexity would be O(log2m*n)
https://www.youtube.com/watch?v=JXU4Akft7yk&t=345s
Maths for DSA:
Left shift (<<) :
<<1 doubles the number
A<<B A*2^B
Right Shift(>>):
>>1 Divides by 2
A>>B A/2^B
0-number = negative of that number
Suppose if we want -10 we do 00000000-00001010
If we add 1 in front of 00000000 it will be ignored since it exceeds 1 byte so 00000000-
000001010 is same as 1 00000000-000001010 as 1 would be ignored
We use 2’s complement for converting a number to it’s negative because 0=-0
For n bits range is -2^n-1 to 2^n-1 -1.
No:of digits in base b of number n
int(logbn)+1
Sum of each row in pascal triangle
=2^n-1
=1<<(n-1)
0 is exception case
Calculation of a^b in O(logb) time
this converts integer to
binary string
No:of bits which are set in a number
both loops gives same output
XOR of 0 till a
Printing all primes less than or equal to n
Newton Raphson Method for Finding square root:
A*B=HCF*LCM
Recursion:
F(n)=F(n-1)+F(n-2) Linear Recurrence relationSame functions are being
called again and again to avoid this we use DP
F(n) =O(1)+F(n/2) Divide and Conquer recurrence relation.
For recursion space complexity = O(height of the recursion tree)
Using external variable
Using helper functions
Palindrome or not
JAVA
Way -2
No:of Zeroes in a Number:
We can either use count as an argument and use helper function or use count as an external
variable.
Initially Count =0
If we take count as an argument Then F(N,0) will call F(N/10,++count) id digit is 0 or else
F(N/10,count) . Use ++count or count+1 do not use count++.
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero
To check Whether array is sorted or not using recursion
Find an element using linear search in recursion
Searching from last
Multiple Occurrences:
Copy of ref to list is being passed so all changes will be reflected in above.
What If we don’t want to take list as an argument but want to return arraylist then
The above is not optimized because we are creating array list for each step in recursive
tree.
Find an element in Rotated sorted array
Skip a character in a given string and form a new one
Skip a string
If we want to skip App but not Apple
We can get all subsequences using below recursion
O/P:-
If we change the order the
o/p would be
If we created an arraylist for each it looks like above it is inefficient. If needed, we should
pass it as an argument.
It is somewhat similar to below code where we created new arraylist for every iteration
ASCII value of a character
o/p:-97
o/p:-b
If we want to include ASCII values as well then we should use the code
o/p:-
Using iteration:
In every level above copy + adding current element to all subsets in above copy
Following above process 3 would be added
Time complexity:O(N*2^N)
Space Complexity: O(N*2^N);
When you find a duplicate element only add it to the newly created subset. -->This only
works if duplicates are together i.e works for [1,2,2] but not for [2,1,2] i.e array should be
sorted.
For Permuations and Combinations , Recursion call can have more than 2 sub calls so we use
for loop along with Recursion and the no:of calls =size of processes string+1
p means processed string above
up means unprocessed
s.substr(0, 0) effectively returns an empty string because it starts at index 0 and has a length of
0.
IF we use arraylist to store permutations
To count the no:of permutations we can use below code
Permutations of an array:
Way-1 using an extra array
Question: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
description/
Answer: https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/blob/main/lectures/14-
recursion/code/src/com/kunal/strings/PhonePad.java
Question: https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/
description/
Answer: https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/blob/main/lectures/14-
recursion/code/src/com/kunal/strings/Dice.java
Sliding Window and Two-Pointer Problems:
Identification: subarray/substring
Fixed subarray size/sub stringfind something
Given a result find variable window size
Shortest/Minimum window condition
No: of Subarrays Where <condition>
Backtracking:
If we consider first row as n and first column as n in a n*n matrix
And if we can only go right or down then no: of paths to reach last block.
If we wanna print the path then
We can also write above code using a list
If diagonal path is also allowed then
If there are is a restriction in a maze like we are not supposed to enter a block here in this
case it’s board[1][1].
If all paths are allowed then we will go into an recursion that will never end because we will
go to the same path again and again to avoid this we can mark the cells that we already
traversed.
All cells that are visited mark them as false
Making cell=false means we have that cell in the current path and if that path is over this cell
must be made true again to include it in other paths. i.e while you move back we restore
maze to as it was This is backtracking.
DP-Optimization Problems
BT-Combinations ProblemsControlled Recursion + Pass by Referencewe need Backtracking
when pass by reference is used.
BT problem TypesChoice + Decision, All combinations or All Paths or Valid Solutions, Controlled
Recursion, No:of choices are large and might vary for each recursive step.
Sometimes BT problems can be solved using greedy and if greedy doesn’t work then BT must be used
Rat in a Maze:
https://takeuforward.org/data-structure/rat-in-a-maze/
Printing Subsequences:
o/p:
If we want in the reverse manner we can use below code
If we want the count of subsequences resulting in the given sum we can use below code
If array contains positives only we can also use the base condition if(s>sum) return 0; in the
above code.
If we want to print just 1 result instead of all combinations, we can use below code
Heap & Priority Queue:
If we want the smallest element then we should use max heap and for largest element we
should use min heap for optimized solution
In C++, the std::priority_queue is a container adaptor that provides a priority queue interface.
The std::priority_queue uses another container to store the elements, and it maintains the
heap property using the specified comparison function.
priority_queue<int, vector<int>, greater<int>> pq; Means min_heap
Dynamic Programming:
Top Down: Recursion
Answer to base case
Bottom up: Tabulation
Base case to Answer
https://takeuforward.org/data-structure/dynamic-programming-introduction/
Recursion: All possible Ways, Count all ways
DP: - usually Best way
Memoization to tabulation:
Base case
Start from Reverse of changing parameters
Copy the recurrence
e.g:
https://www.youtube.com/watch?
v=EgG3jsGoPvQ&list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY&index=4
https://www.naukri.com/code360/problems/frog-jump_3621012
Greedy does not work
using Recursion Using steps to solve the problem after identification as given above
if(index==0) return 0;
f(n-1) gives answer represented problem in term of indices
# Trying all possible ways
single_jump = f(ind-1)+abs(a[ind]-a[ind-1]);
if(ind>1)
double_jump = f(ind-2)+ abs(a[ind]-a[ind-2]);
# count or Find min or max
Question asked us min so we calculate min
return min (single_jump, double_jump)
we can see there are overlapping subproblems, so we use Memoization.
Conversion to Tabulation:
We fill index 0 then 1 then 2 … then n-1
If(ind==0) return 0; dp[0] =0;
The remaining steps will be executed for ind =1,2,3 .. n-1
for(int i=1 n-1) {
single_jump = dp[ind-1]+ abs(a[ind]-a[ind-1])
If(ind>1)
double-jump= dp[ind-2]+ abs(a[ind]-a[ind-1])
dp[ind]=min(single_jump, double_jump);
}
If there is ind-1 and ind-2 there is always chance of space optimization.
Extension of above problem : https://takeuforward.org/data-structure/dynamic-programming-frog-jump-with-
k-distances-dp-4/
Problem 1: https://leetcode.com/problems/climbing-stairs/
Using only Recursion gives TLE:
Top Down with Memoization:
Tabulation (Bottom-up Approach)
Space Optimized : Bottom up Approach
Problem 2: https://leetcode.com/problems/min-cost-climbing-stairs/description/
Top Down(Recursion+Memoization—Giving TLE for large n)
Way-2
Bottom up Approach
Optimized space: (Bottom Up)
Problem: https://www.naukri.com/code360/problems/ninja-s-training_3621003
https://takeuforward.org/data-structure/dynamic-programming-ninjas-training-dp-7/
https://www.youtube.com/watch?
v=AE39gJYuRog&list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY&index=8
Problem: Subset sum equals to k
https://takeuforward.org/data-structure/subset-sum-equal-to-target-dp-14/
Step 1: Express in terms of indices
In subsequences if we have a target then while expressing in terms of indices, we should
consider both array index and also target as index.
Step 2: Explore possibilities of that index
A[index] could be part of the subsequence or could not be part of the subsequence
F(n-1,target) include index and not include index has overlapping subproblems so we
use memorization.
Tabulation:
While converting to tabulation index comes from n-1 to 0 in Recursion so in tabulation it as
to go from 0 to n and target goes from k to 0 so in tabulation it goes from 0 to k
For target =0 we can take no elements and the output is true for all
For(int i=0;i<n;i++)
dp[i][0] =true;
dp[0][arr[0]] = true;
since we already handled cases for ind=0 and target =0;
Since it has ind-1 we can space optimize
Space optimization code:
Memoization To store values we create a matrix of dimensions with values that are
changing.
dp[n+1][w+1] we can create with constant size using constraints.
Top-Down Base Condition Bottom-up Initialization
Stack & Queue: