0% found this document useful (0 votes)
21 views395 pages

DSA450

The document discusses various algorithms and data structures topics including arrays, strings, searching and sorting, linked lists, stacks, queues, trees, graphs, and dynamic programming. It provides lists of problems and concepts covered under each topic area in a spaced repetition format to aid in learning and reviewing the material.

Uploaded by

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

DSA450

The document discusses various algorithms and data structures topics including arrays, strings, searching and sorting, linked lists, stacks, queues, trees, graphs, and dynamic programming. It provides lists of problems and concepts covered under each topic area in a spaced repetition format to aid in learning and reviewing the material.

Uploaded by

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

Topic:

Array
Array
Array
Array
Array

Array

Array
Array
Array

Array

Array

Array

Array

Array

Array

Array
Array

Array

Array

Array

Array

Array

Array

Array

Array

Array

Array

Array

Array

Array
Array

Array

Array

Array

Array

Array

Matrix

Matrix

Matrix
Matrix

Matrix

Matrix

Matrix

Matrix

Matrix
Matrix

Matrix

Matrix

String
String
String
String

String

String

String

String

String

String

String

String

String
String

String

String

String

String

String

String

String

String

String

String

String

String

String
String

String

String

String

String

String

String

String

String

String

String
String

String

String

String

String

Searching & Sorting


Searching & Sorting

Searching & Sorting

Searching & Sorting


Searching & Sorting
Searching & Sorting
Searching & Sorting
Searching & Sorting

Searching & Sorting

Searching & Sorting


Searching & Sorting
Searching & Sorting

Searching & Sorting

Searching & Sorting

Searching & Sorting

Searching & Sorting


Searching & Sorting

Searching & Sorting

Searching & Sorting

Searching & Sorting

Searching & Sorting

Searching & Sorting

Searching & Sorting

Searching & Sorting

Searching & Sorting

Searching & Sorting

Searching & Sorting


Searching & Sorting
Searching & Sorting

Searching & Sorting

Searching & Sorting


Searching & Sorting
Searching & Sorting
Searching & Sorting
Searching & Sorting
Searching & Sorting

Searching & Sorting

LinkedList

LinkedList

LinkedList

LinkedList

LinkedList
LinkedList
LinkedList
LinkedList
LinkedList
LinkedList
LinkedList
LinkedList
LinkedList
LinkedList

LinkedList

LinkedList
LinkedList

LinkedList
LinkedList
DoubleLinkedList
DoubleLinkedList
DoubleLinkedList

DoubleLinkedList

DoubleLinkedList
DoubleLinkedList

DoubleLinkedList

LinkedList
LinkedList

LinkedList

LinkedList

LinkedList

LinkedList
LinkedList
LinkedList
LinkedList

LinkedList
Binary Trees

Binary Trees
Binary Trees

Binary Trees

Binary Trees

Binary Trees

Binary Trees

Binary Trees

Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees

Binary Trees

Binary Trees
Binary Trees
Binary Trees

Binary Trees

Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees
Binary Trees

Binary Trees

Binary Trees

Binary Trees
Binary Trees

Binary Trees

Binary Trees
Binary Trees

Binary Trees

Binary Trees

Binary Trees
Binary Search Trees

Binary Search Trees

Binary Search Trees


Binary Search Trees
Binary Search Trees
Binary Search Trees

Binary Search Trees

Binary Search Trees


Binary Search Trees
Binary Search Trees
Binary Search Trees

Binary Search Trees

Binary Search Trees


Binary Search Trees
Binary Search Trees
Binary Search Trees

Binary Search Trees

Binary Search Trees


Binary Search Trees
Binary Search Trees

Binary Search Trees


Greedy

Greedy

Greedy

Greedy
Greedy

Greedy

Greedy

Greedy
Greedy

Greedy

Greedy

Greedy

Greedy

Greedy

Greedy

Greedy
Greedy
Greedy
Greedy
Greedy
Greedy

Greedy

Greedy
Greedy
Greedy
Greedy
Greedy
Greedy

Greedy

Greedy
Greedy
Greedy
Greedy
Greedy
Greedy

BackTracking
BackTracking
BackTracking

BackTracking

BackTracking
BackTracking
BackTracking
BackTracking
BackTracking

BackTracking

BackTracking

BackTracking
BackTracking
BackTracking
BackTracking
BackTracking
BackTracking
BackTracking
BackTracking

Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues


Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues


Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues


Stacks & Queues
Stacks & Queues
Stacks & Queues
Stacks & Queues
Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues


Stacks & Queues

Stacks & Queues

Stacks & Queues


Stacks & Queues
Stacks & Queues
Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues

Stacks & Queues

Heap prerequisites:

Heap
Heap

Heap

Heap
Heap

Heap

Heap

Heap

Heap

Heap

Heap

Heap

Heap

Heap
Heap

Heap
Heap
Heap

Graph

Graph

Graph

Graph

Graph

Graph

Graph
Graph

Graph

Graph
Graph
Graph
Graph
Graph
Graph

Graph

Graph
Graph
Graph
Graph

Graph

Graph

Graph
Graph

Graph

Graph
Graph
Graph
Graph

Graph

Graph

Graph
Graph

Graph

Graph

Graph
Graph
Graph
Graph

Graph

Graph

Graph

Graph
Graph
Graph
Graph

Graph

Graph

Trie

Trie

Trie

Trie

Trie
Trie
Trie

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming
Dynamic Programming

Dynamic Programming
Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming
Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming
Dynamic Programming
Dynamic Programming
Dynamic Programming
Dynamic Programming
Dynamic Programming

Dynamic Programming

Dynamic Programming
Dynamic Programming
Dynamic Programming
Dynamic Programming
Dynamic Programming
Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming
Dynamic Programming
Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming
Dynamic Programming
Dynamic Programming
Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming
Dynamic Programming

Dynamic Programming

Dynamic Programming

Dynamic Programming
Dynamic Programming

Dynamic Programming

Dynamic Programming

Basics

Bit Manipulation

Bit Manipulation

Bit Manipulation

Bit Manipulation
Bit Manipulation

Bit Manipulation

Bit Manipulation
Bit Manipulation

Bit Manipulation

Bit Manipulation

Bit Manipulation

Bit Manipulation
Bit Manipulation

Math
Questions by Love Babbar:
Youtube Channel: https://www.youtube.com/channel/UCQHLxxBFrbfdrk1jF0moTpw

Problem:

Reverse the array


Find the maximum and minimum element in an array
Find the "Kth" max and min element of an array
Given an array which consists of only 0, 1 and 2. Sort the array without using any sortin
Move all the negative elements to one side of the array

Find the Union and Intersection of the two sorted arrays.

Write a program to cyclically rotate an array by one.


find Largest sum contiguous Subarray [V. IMP]
Minimise the maximum difference between heights [V.IMP]
Minimum no. of Jumps to reach end of an array

find duplicate in an array of N+1 Integers [V V.IMP] - one number can repeat multiple ti

Merge 2 sorted arrays without using Extra space [V IMP]

Kadane's Algo [V.V.V.V.V IMP]

Merge Intervals [V.V. Imp]

Next Permutation [V. IMP]

Count Inversion
Best time to buy and Sell stock (or Maximum difference between two elements such th

find all pairs on integer array whose sum is equal to given number (Pair sum)
find common elements In 3 sorted arrays

Rearrange the array in alternating positive and negative items with O(1) extra space - s

Find if there is any subarray with sum equal to 0

Find factorial of a large number

find maximum product subarray

Find longwcoinsecutive subsequence

Given an array of size n and a number k, fin all elements that appear more than " n/k "

Maximum profit by buying and selling a share atmost twice

Find whether an array is a subset of another array


Find the triplet that sum to a given value

Trapping Rain water problem

Chocolate Distribution problem


Smallest Subarray with sum greater than a given value (k) [IMP](1c) Any sub array / sm

Three way partitioning of an array around a given value

Minimum swaps required bring elements less equal K together [Imp]

Minimum no. of merge operations required to make an array palindrome

Median of 2 sorted arrays of equal size

Median of 2 sorted arrays of different size [IMP]

Spiral traversal on a Matrix

Search an element in a matriix (Binary Search in a Matrix!)

Find median in a row wise sorted matrix


Find row with maximum no. of 1's
Print elements in sorted order from row-column wise sorted matrix

Maximum size rectangle [IMP]


Find a specific pair in matrix

Rotate matrix by 90 degrees

Kth smallest element in a row-column wise sorted matrix


Find a common element in all rows of a given row-wise sorted matrix
Common elements in all rows of a given matrix

Submatrix sum queries [IMP] (uses auxilary matrix ~equivalent to prefix sum array in 1d

Reverse a String
Check whether a String is Palindrome or not
Find Duplicate characters in a string
Why strings are immutable in Java?
Write a Code to check whether one string is a rotation of another

Write a Program to check whether a string is a valid shuffle of two strings or not

Count and Say problem

Longest palindromic substring (LPS)

Find Longest Recurring Subsequence in String

Print all Subsequences of a string.

Print all the permutations of the given string


Split the Binary string into two substring with equal 0’s and 1’s
Word Wrap Problem [VERY IMP].
EDIT Distance [Very Imp]

Find next greater number with same set of digits. [Very Very IMP]

Balanced Parenthesis problem.[Imp]

Word break / ilikesamsung Problem[ Very Imp]

Rabin Karp Algo

KMP Algo

Convert a Sentence into its equivalent mobile numeric keypad sequence.

reversals of brackets to balance string

Count All Palindromic Subsequence in a given String.

Count of number of given string in 2D character array

Search a Word in a 2D Grid of characters.

Boyer Moore Algorithm for Pattern Searching.


Converting Roman Numerals to Decimal
Longest Common Prefix
Number of flips to make binary string alternate
Find the first repeated word in string.

Minimum number of swaps for bracket balancing.

Find the longest common subsequence between two strings.

Program to generate all possible valid IP addresses from given string (Valid IP Address)

Write a program tofind the smallest window that contains all characters of string itself.

Rearrange characters in a string such that no two adjacent are same

Shortest Palindrome - Minimum characters to be addedat front to make string palindro

Given a sequence of words, print all anagrams together

Minimum window substring - (Find the smallest window in a string containing all chara

(a)Recursively remove all adjacent duplicates


String matching where one string contains wildcard characters

Function to find Number of customers who could not get a computer

Minimum number of operations to transform one string to another by moving chars to

Check if two given strings are isomorphic to each other


Recursively print all sentences that can be formed from list of word lists

Find first and last positions of an element in a sorted array


Find a Fixed Point (Value equal to index) in a given array
Find pivot(max) or min element in a sorted and rotated array
Search in a rotated sorted array
square root of an integer
Maximum and minimum of an array using minimum number of comparisons
Optimum location of point to minimize total distance
Find the repeating and the missing
find majority element
Searching in an array where adjacent differ by at most k
find a pair with a given difference
find four elements that sum to a given value
maximum sum such that no 2 elements are adjacent (Stickler Theif)

Count triplet with sum smaller than a given value

merge 2 sorted arrays

print all subarrays with 0 sum


Product array Puzzle

Sort array according to count of set bits

Sort a nearly sorted (or K sorted) array [V IMP]

minimum no. of swaps required to sort the array [V IMP]


Bishu and Soldiers
Rasta and Kheshtak (Biggest Common Subsquare (BCS))
Kth smallest number again
K-th Element of Two Sorted Arrays
Aggressive cows

Book Allocation Problem (BAP) [V IMP]

EKOSPOJ:
Job Scheduling Algo
Missing Number in AP

Smallest number with atleastn trailing zeroes infactorial

Painters Partition Problem


ROTI-Prata SPOJ
DoubleHelix SPOJ
Count of Subset Sums
Find the inversion count
Implement Merge-sort in-place
Partitioning and Sorting Arrays with Many Repeated Entries

Write a Program to reverse the Linked List. (Both Iterative and recursive)
Reverse a Linked List in group of Given Size. [Very Imp]
Write a program to Detect loop in a linked list.

Write a program to Delete loop in a linked list [V Imp]

Find the starting point of the loop.


Remove Duplicates in a sorted Linked List.
Remove Duplicates in a Un-sorted Linked List.
Write a Program to Move the last element to Front in a Linked List.
Add “1” to a number represented as a Linked List.
Add two numbers represented by linked lists.
Intersection of two Sorted Linked List.
Intersection Point of two Linked Lists.
Merge Sort For Linked lists.[Very Important]
Quicksort for Linked Lists.[Very Important]
Find the middle Element of a linked list.
Check if a linked list is a circular linked list.
Split a Circular linked list into two halves.

Write a Program to check whether the Singly Linked list is a palindrome or not.
Deletion from a Circular Linked List.
Reverse a Doubly Linked list.
Find pairs with a given sum in a DLL.
Count triplets in a sorted DLL whose sum is equal to given value “X”.
Sort a “k”sorted Doubly Linked list.[Very IMP]
Rotate DoublyLinked list by N nodes.
Reverse a Doubly Linked list in group of Given Size.[Very IMP]

Find the first non-repeating character from a stream of characters

Can we reverse a linked list in less than O(n) ?


Why Quicksort is preferred for Arrays and Merge Sort for LinkedLists ?

Flatten a Linked List

Sort a LL of 0's, 1's and 2's

Clone a linked list with next and random pointer

Merge K sorted Linked list


Multiply 2 no. represented by LL
Delete nodes which have a greater value on right side
Segregate even and odd nodes in a Linked List

Program for n’th node from the end of a Linked List


level order traversal

Reverse Level Order traversal


Height of a tree

Diameter of a tree

Mirror of a tree
Inorder Traversal of a tree both using recursion and Iteration [Imp]

Preorder Traversal of a tree both using recursion and Iteration [V Imp]

Postorder Traversal of a tree both using recursion and Iteration [V Imp]


Left View of a tree
Right View of Tree
Top View of a tree
Bottom View of a tree
Zig-Zag traversal of a binary tree
Check if a tree is balanced or not
Diagnol Traversal of a Binary tree
Boundary traversal of a Binary tree
Construct Binary Tree from String with Bracket Representation
Convert Binary tree into Doubly Linked List
Convert Binary tree into Sum tree
Construct Binary tree from Inorder and preorder traversal

Find minimum swaps required to convert a Binary tree into BST

Check if Binary tree is Sum tree or not


Check if all leaf nodes are at same level or not
Serialize and Deserialize a Binary Tree [IMP] - Modified preorder

Check if a Binary Tree (S) is a sub-tree of another Binary Tree (T)

Check if a Binary Tree contains duplicate subtrees of size 2 or more [ IMP ]


Find all Duplicate subtrees in a Binary tree [ IMP ]
Check if 2 trees are mirror or not
Sum of Nodes on the Longest path from root to leaf node
Check if given graph is tree or not. [ IMP ]
Find Largest subtree sum in a tree
Maximum Sum of nodes in Binary tree such that no two are adjacent

Print all "K" Sum paths in a Binary tree (Path Sum III)

Find LCA in a Binary tree

Check if two nodes are on same path in a tree


Find distance between 2 nodes in a Binary tree

Kth Ancestor of node in a Binary tree [IMP]

Nodes at given distance in binary tree [IMP]


Tree Isomorphism Problem
inorder sucessor in a Binary Tree

Populate Inorder successor of all nodes

Inorder predecessor in a Binary Tree


Find a value in a BST

Deletion of a node in a BST

Find min and max value in a BST


Find inorder successor and inorder predecessor in a BST
Check if a tree is a BST or not
Construct BST from preorder traversal [IMP] (In O(N))
Check preorder is valid or not
Check whether BST contains Dead end
Find LCA of 2 nodes in a BST
Convert Binary tree into BST
Convert a normal BST into a AVL Tree (Balanced BST)

Merge two BST [ V.V.V IMP ] (Important to do using iterative inorder)

Find Kth largest element in a BST


Find Kth smallest element in a BST
Count pairs from 2 BST whose sum is equal to given value "X" (Brothers From Different
Flatten BST to sorted list

Find the median of BST in O(n) time and O(1) space [Use Morris Traversal for O(1) spac

Count BST nodes that lie in a given range


Replace every element with the least greater element on its right [Application]
Given "n" appointments, find the conflicting appointments (Interval Tree) [Application]

Largest BST in a Binary Tree [ V.V.V.V.V IMP ]


Activity Selection Problem

Job SequencingProblem

Huffman Coding

Water Connection Problem


Fractional Knapsack Problem

Greedy Algorithm to find Minimum number of Coins (Canonical System)

Maximum trains for which stoppage can be provided


Minimum Platforms Problem
Buy Maximum Stocks if i stocks can be bought on i-th day
Find the minimum and maximum amount to buy all N candies

Minimize Cash Flow among a given set of friends who have borrowed money from each

Minimum Cost to cut a board into squares

Check if it is possible to survive on Island

Find maximum meetings in one room

Maximum product subset of an array

Maximize array sum after K negations


Maximize the sum of arr[i]*i
Maximum sum of absolute difference of an array
Maximize sum of consecutive differences in a circular array
Minimum sum of absolute difference of pairs of two arrays
Program for Shortest Job First (or SJF) CPU Scheduling

Program for Least Recently Used (LRU) Page Replacement algorithm

Smallest subset with sum greater than all other elements


Chocolate Distribution Problem
DEFKIN -Defense of a Kingdom
DIEHARD -DIE HARD
GERGOVIA -Wine trading in Gergovia
Picking Up Chicks
CHOCOLA –Chocolate
ARRANGE -Arranging Amplifiers
K Centers Problem
Minimum Cost of ropes
Find smallest number with given number of digits and sum of digits
Rearrange characters in a string such that no two adjacent are same
Find maximum sum possible equal sum of three stacks

Rat in a maze Problem


Printing all solutions in N-Queen Problem
Word Break Problem using Backtracking

Remove Invalid Parentheses

Sudoku Solver
m Coloring Problem
Print all palindromic partitions of a string
Subset Sum Problem
The Knight’s tour problem
Tug of War

Find shortest safe route in a path with landmines

Combinational Sum
Find Maximum number possible by doing at-most K swaps
Print all permutations of a string
Find if there is a path of more than k length from a source
Longest Possible Route in a Matrix with Hurdles
Print all possible paths from top left to bottom right of a mXn matrix
Partition of a set intoK subsets with equal sum
Find the K-th Permutation Sequence of first N natural numbers

Implement Stack from Scratch

Implement Queue from Scratch

Implement 2 stack in an array

Design a stack that supports find the middle element in O(1)

Implement "N" stacks in an Array

Valid or Balanced parenthesis/brackets [IMP]

Reverse a String using Stack


Design a Stack that supports getMin() in O(1) time and (a)O(n) and (b)O(1) extra space.

Find the next Greater element (NGE)-- Monotonic Stack

The celebrity Problem

Infix to Postfix

Evaluation of Postfix expression

Implement a method to insert an element at its bottom without using any other data s

Reverse a stack using recursion

Sort a Stack using recursion


Merge Overlapping Intervals

Largest rectangular Area in Histogram-- Monotonic Stack

Longest Valid Parenthesis [IMP]

Expression contains redundant bracket or not


Implement Stack using Queue
Implement Stack using Deque
Stack Permutations (Check if an array is stack permutation of other)
Implement Queue using Stack
Implement "n" queue in an array

Implement a Circular queue

LRU Cache Implementation

Reverse a Queue using recursion

Reverse the first “K” elements of a queue


Interleave the first half of the queue with second half

Find the first circular tour that visits all Petrol Pumps

Minimum time required to rot all oranges


Distance of nearest cell having 1 in a binary matrix
First negative integer in every window of size “k”
Check if all levels of two trees are anagrams or not.

Sum of minimum and maximum elements of all subarrays of size “k”.

Minimum sum of squares of character counts in a given string after removing “k” chara

Queue based approach or first non-repeating character in a stream.

Prices with special discount - (Next Smaller Element)

Read the following articles & watch videos to get the understanding of Heap before solving problem
Implement a Maxheap/MinHeap using arrays and recursion.
Sort an Array using heap. (HeapSort)

Sliding Window Maximum :- Maximum of all subarrays of size k [IMP] -- Monotonic Deq

“k” largest element in an array


Kth smallest and largest element in an unsorted array

Merge “K” sorted arrays. [ IMP ]

Merge 2 Binary Max Heaps

Kth largest sum continuous subarrays

Leetcode- reorganize strings

Merge “K” Sorted Linked Lists [V.IMP]

Smallest range in “K” Lists

Median in a stream of Integers

Check if a Binary Tree is Heap

Connect “n” ropes with minimum cost


Convert BST to Min Heap

Convert min heap to max heap


Rearrange characters in a string such that no two adjacent are same.
Minimum sum of two numbers formed from digits of an array

Create a Graph, print it

Implement BFS algorithm

Implement DFS Algo

Detect Cycle in UnDirected Graph using BFS/DFS Algo

Detect Cycle in Directed Graph using DFS Algo

Implement Topological Sort using DFS

Implement Topological Sort using BFS (Kahn's algo) /Detect cycle in directed graph usin
Shortest path in Undirected graph without weights - BFS

Dijkstra algo/Shortest path in Undirected graph with weights

Search in a Maze
Minimum Step by Knight
flood fill algo
Clone a graph
Making wired Connections (Redundant edges)
word Ladder

Minimum time taken by each job to be completed given by a Directed Acyclic Graph

Find whether it is possible to finish all tasks or not from given dependencies
Count Connected Components (can be done using DFS/BFS)
Find the no. of Isalnds
Given a sorted Dictionary of an Alien Language, find order of characters

Implement Kruksal’sAlgorithm

Implement Prim’s Algorithm

Total no. of Spanning tree in a graph


Implement Bellman Ford Algorithm ( Shortest path + Detect Negative cycle)

Print negative weight cycle in Directed graph using Bellman Ford

Implement Floyd warshallAlgorithm


Travelling Salesman Problem
Graph ColouringProblem
Snake and Ladders Problem

Count Strongly connected Components(Tarjan's algorithm)

Articulation points (Cut Vertex) & Critical Connections in a Network (Bridge in Graph)

Count Strongly connected Components(Kosaraju Algo)


Check whether a graph is Bipartite or Not

Shortest path in DAG using Topological Sort (Linear time, better than Dijkstra's and BF's

Longest path in a DAG


Journey to the Moon
Cheapest Flights Within K Stops
Oliver and the Game
Water Jug problem using BFS

Find if there is a path of more thank length from a source

M-ColouringProblem
Minimum edges to reverse o make path from source to destination
Paths to travel each nodes using each edge(Seven Bridges)
Vertex Cover Problem
Chinese Postman or Route Inspection
Number of Triangles in a Directed and Undirected Graph

Minimise the cashflow among a given set of friends who have borrowed money from e
Two Clique Problem

Theoritical Data structure questions:


Construct a trie from scratch

Find shortest unique prefix for every word in a given list

Word Break Problem | (Trie solution)

Given a sequence of words, print all anagrams together

Implement a Phone Directory


Print unique rows in a given boolean matrix
Auto_Complete word suggestion system

Rod Cutting and its slight variation

Coin ChangeProblem II (all possible ways to make change)

Knapsack Problem (01 KS)

Binomial CoefficientProblem
Permutation CoefficientProblem

Program for nth Catalan Number [IMP] (Please see application questions-->)
Matrix Chain Multiplication [V.Imp] (MCM)
Edit Distance

Partition Subset/Subsequence Sum Problem (re-phrasing of Subset Sum K(SS)) [Imp]

Friends Pairing Problem


Gold Mine Problem
Assembly Line SchedulingProblem

Painting the Fenceproblem[Imp]

Maximize The Cut Segments


Longest Common Subsequence[V.Imp] (LCS)

Longest Repeated Subsequence

Longest Increasing Subsequence[V.Imp] (LIS)

Space Optimized Solution of LCS

LCS (Longest Common Subsequence) of three strings


Maximum Sum Increasing Subsequence (MSIS)
Count all subsequences having product less than K
Longest subsequence such that difference between adjacent is one
Maximum subsequence sum such that no three are consecutive [IMP]
Egg Dropping Problem

Maximum Length Chain of Pairs

Maximal Square - Maximum size square sub-matrix with all 1s


Maximum sum of pairs with specific difference
Min Cost PathProblem
Maximum difference of zeros and ones in binary string
Minimum number of jumps to reach end
Minimum cost to fill given weight in a bag
Minimum removals from array to make max –min <= K

Longest Common Substring (LC -Substring) [IMP]


Count number of ways to reach a given score in a game

Count Balanced Binary Trees of Height h

LargestSum Contiguous Subarray [V>V>V>V IMP ]


Smallest sum contiguous subarray
Unbounded Knapsack (Repetition of items allowed) (Unbounded KS)

Word Break Problem (WB) / ilikesamsung [IMP]

Largest Independent Set Problem

Partition problem
Longest Palindromic Subsequence [Imp] (LPS*)
Count All Palindromic Subsequence in a given String
Longest Palindromic Substring [Imp] (LPS)

Longest alternating subsequence

Weighted Job Scheduling

Coin game winner where every player has three choices [IMP] (Beerus-Whis problem)

Count Derangements (Permutation such that no element appears in its original position
Maximum profit by buying and selling a share at most twice [ IMP ] (BS-2) - (Not a Dp p

Optimal Strategy for a Game

Optimal Binary Search Tree [IMP] (OBST)

Palindrome Partitioning Problem (PP II)

Text Justification / Word Wrap Problem

Mobile Numeric Keypad Problem [ IMP ]


Boolean Parenthesization Problem

Maximum sum rectangle in a 2D matrix

Largest area rectangular sub-matrix with equal number of 1’s and 0’s [ IMP ]

Largest rectangular sub-matrix whose sum is 0


Maximum profit by buying and selling a share at most k times

Interleaving String

Maximum Length of Pair Chain

pep coding playlist is gold for bit manipulation


Right most set bit mask in O(1) (RSB)

Count set bits in an integer

Find the two non-repeating elements in an array of repeating elements

Count number of bits to be flipped to convert A to B (Hamming Distance)


Count total set bits in all numbers from 1 to n
Program to find whether a no is power of two
Find position of the only set bit
Copy set bits in a range

Divide two integers without using multiplication, division and mod operator

Calculate square of a number without using *, / and pow()


Power Set
Count Triplets That Can Form Two Arrays of Equal XOR
Reduce a number to 1 by performing given operations
Reverse Integer (handle overflow)
N Not
M Moderate
V Very
Done Imp Done on

yes N 4/13/2021
yes M 4/13/2021
yes V 4/13/2021
yes V 4/13/2021
yes M 4/13/2021

yes M 4/13/2021

yes N 4/14/2021
yes V 4/14/2021
<->

yes M 4/15/2021

yes V 4/15/2021

yes V 4/15/2021

yes V 4/15/2021

yes V 4/15/2021

yes V 4/15/2021

yes V 4/15/2021
yes M 4/15/2021

yes V 4/16/2021
yes N 4/19/2021

yes V 4/16/2021

yes V 4/16/2021

yes N 4/19/2021

yes V 4/17/2021

yes V 4/17/2021

yes M 4/17/2021

yes V 4/17/2021

yes N 4/17/2021
yes N 4/19/2021

yes V 4/18/2021

yes V 4/18/2021
yes V 4/18/2021

yes N 4/18/2021

yes V 4/19/2021

yes V 4/19/2021

yes V 4/18/2021

yes V 4/19/2021

yes M 4/19/2021

yes M 4/20/2021

<->
yes M 4/20/2021
yes V 4/21/2021

yes V 4/21/2021
<->

yes 4/22/2021

yes 4/22/2021
yes 4/22/2021
yes 4/22/2021

yes 5/24/2021

yes N 4/22/2021
yes N 4/22/2021
yes N 4/22/2021
yes 4/22/2021
yes M 4/22/2021

yes M 4/23/2021

yes M 4/23/2021

yes V 4/23/2021

yes M 4/23/2021

yes V 4/23/2021

yes V 4/24/2021
yes N 4/24/2021
yes V
yes V 4/24/2021

yes V 4/24/2021

yes V 4/24/2021

yes V 4/25/2021

yes 4/25/2021

yes V 4/26/2021

yes N 4/26/2021

yes V 4/27/2021

yes V 5/2/2021

yes M 5/2/2021

yes N 5/8/2021

<->

yes M 5/4/2021
yes N 5/2/2021
yes N 5/3/2021
yes N 5/4/2021

yes V 5/4/2021

yes V 4/23/2021

yes V 7/31/2021

yes M 5/6/2021

yes M 5/8/2021

yes V 5/7/2021

yes N 5/7/2021

yes V 5/9/2021

yes M 5/7/2021
yes V 5/8/2021

yes N 5/8/2021

yes V 5/8/2021

yes N 5/8/2021
yes N 5/8/2021

yes V 6/30/2021
yes 6/30/2021
yes V 7/4/2021
yes V 6/30/2021
yes M 7/1/2021
yes M 7/1/2021
<->
yes V 7/2/2021
yes V 7/2/2021
yes M 7/2/2021
yes V 7/2/2021
yes M 7/2/2021
yes M 7/2/2021

yes M 7/2/2021

yes V 7/11/2021

yes V 7/3/2021
yes N 7/3/2021

yes M 7/4/2021

yes V 7/4/2021

yes V 6/5/2021
yes M 7/11/2021
<->

yes 7/4/2021
<->

yes V 7/5/2021

yes V 7/5/2021

yes V 7/5/2021
yes 7/7/2021
yes V 7/6/2021

yes 7/7/2021

yes V 7/5/2021
yes 7/8/2021
yes 7/8/2021
yes 7/10/2021
yes 7/10/2021
yes 7/10/2021
yes 7/11/2021

yes V 5/26/2021
yes V 5/26/2021
yes V 5/26/2021

yes V 5/27/2021

yes V 5/27/2021
yes N 5/27/2021
yes N 5/27/2021
yes N 5/27/2021
yes N 5/27/2021
yes M 5/28/2021
yes N 5/28/2021
yes V 5/28/2021
yes V 5/28/2021
<->

yes M 5/28/2021
yes 5/28/2021
yes 5/29/2021

yes 5/29/2021
yes 5/29/2021
yes 5/29/2021
yes 5/30/2021
yes 5/30/2021
yes 5/31/2021
yes 6/1/2021
yes 6/1/2021

yes 6/1/2021

<->
<->

yes 5/29/2021

yes 5/29/2021

yes 5/30/2021

yes 5/29/2021
yes 5/30/2021
yes 5/30/2021
yes 5/30/2021

yes 5/30/2021
yes V 6/2/2021

yes M 6/2/2021
yes M 6/2/2021

yes V 6/2/2021

yes M 6/2/2021
yes V 6/3/2021

yes V 6/3/2021

yes V 6/3/2021
yes M 6/3/2021
yes M 6/3/2021
yes M 6/3/2021
yes M 6/4/2021
yes M 6/4/2021
yes V 6/4/2021
yes M 6/4/2021
yes V 6/5/2021
yes M 6/5/2021
yes M 6/5/2021
yes N 6/5/2021
yes V 6/5/2021

yes V 6/5/2021

yes N 6/5/2021
yes N 6/5/2021
yes V 6/6/2021

yes M 6/6/2021

yes V 6/6/2021
yes V 6/8/2021
yes N 6/6/2021
yes M 6/6/2021
yes V
yes M 6/6/2021
yes V 6/6/2021

yes V 6/7/2021

yes V 6/7/2021

yes M 6/7/2021
yes V 6/7/2021

yes V 6/8/2021

yes V 6/9/2021
yes 6/8/2021
yes 6/9/2021

yes 6/10/2021

yes
yes 6/9/2021

yes 6/9/2021

yes 6/9/2021
yes V 6/9/2021
yes V 6/9/2021
yes V 6/11/2021
yes V 6/12/2021
yes M 6/13/2021
yes M 6/10/2021
yes 6/11/2021
yes 6/11/2021

yes 6/11/2021

yes 6/12/2021
yes 6/12/2021
yes 6/12/2021
yes 6/13/2021

yes 6/13/2021

yes 6/12/2021
<->
<->

yes 6/12/2021
yes 7/24/2021

yes 7/24/2021

yes 7/24/2021

yes 7/24/2021
yes 7/24/2021

yes 7/25/2021

yes 7/25/2021
yes 7/25/2021
yes 7/25/2021
yes 7/25/2021

yes 6/27/2021
yes 7/26/2021

yes 7/26/2021

yes 7/26/2021

yes 7/26/2021

yes 7/26/2021
yes 7/26/2021
yes 7/26/2021
yes 7/26/2021
yes 7/26/2021
<->

yes 7/27/2021

yes 7/26/2021
yes 7/26/2021
<->
<->
<->
<->

yes 7/26/2021
<->
<->
<->
<->
<->
<->

yes 7/31/2021
yes 7/31/2021
<->

yes M 7/31/2021

yes 7/31/2021
yes 7/31/2021
<->
yes
yes 7/31/2021
yes 7/31/2021

yes 7/31/2021

yes
<->
<->
<->
<->
<->
<->
<->

yes M 7/12/2021

yes V 7/12/2021

yes M 7/12/2021

yes V 7/12/2021

<->

yes V 7/12/2021

yes N 7/12/2021
yes V 7/13/2021

yes V 7/13/2021

yes 7/17/2021

yes V 7/13/2021

yes M 7/13/2021
yes M 7/14/2021

yes V 7/14/2021

yes N 7/14/2021
yes V 7/4/2021

yes V 4/21/2021

yes V 7/14/2021

yes M 7/15/2021
yes M 7/15/2021
yes N 7/17/2021
yes M 7/15/2021
yes M 7/16/2021
<->

yes V 7/12/2021

yes V 7/17/2021

yes N 7/17/2021

yes M 7/17/2021
yes M 7/17/2021

yes V 7/17/2021

yes V 7/17/2021
yes V 7/17/2021
yes V 7/17/2021
yes 7/18/2021

yes M 7/18/2021

yes N 7/18/2021

yes V 7/18/2021

yes M 7/19/2021

g problems:
yes V 7/19/2021
yes V 7/19/2021

yes V 7/18/2021

yes V 7/19/2021
yes M 7/19/2021

yes V 7/19/2021

yes V 7/19/2021

yes 7/19/2021

yes V 7/19/2021

yes M 7/20/2021

yes V 7/20/2021

yes V 7/21/2021

yes V 7/20/2021

yes M 7/20/2021
yes V 7/20/2021

yes 7/21/2021
yes M 7/21/2021
yes M 7/22/2021

yes M 6/13/2021

yes V 6/13/2021

yes V 6/13/2021

yes M 6/13/2021

yes V 6/13/2021

yes V 6/14/2021

yes V 6/14/2021
yes V 6/15/2021

yes V 6/16/2021

yes V 6/16/2021
yes M 6/16/2021
yes M 6/17/2021
yes M 6/17/2021
yes V 6/17/2021
yes M 6/18/2021

yes V 6/20/2021

yes V 6/20/2021
yes 6/20/2021
yes 6/20/2021
yes V 6/20/2021

<->

yes 6/22/2021

yes 6/22/2021
yes 6/26/2021

yes 6/26/2021

<->
<->
yes 6/23/2021
yes 6/23/2021

yes 6/25/2021

yes 6/25/2021

yes 6/25/2021
yes 6/25/2021

yes 6/26/2021

yes 6/26/2021
yes 6/26/2021
yes 6/26/2021
yes 6/27/2021
yes 6/27/2021

yes 6/27/2021

yes 6/23/2021
yes 6/27/2021
<->
<->
<->
yes 6/27/2021

yes 6/27/2021
yes 6/29/2021

yes 7/27/2021

yes 7/27/2021

<->

yes 7/29/2021

yes 7/29/2021
yes 7/30/2021
yes 7/30/2021

yes V 5/12/2021

yes V 5/12/2021

yes 5/12/2021
yes 5/12/2021

yes 5/13/2021
yes V 5/13/2021
yes V 5/14/2021

yes V 5/15/2021

yes M 5/15/2021
yes M 5/15/2021
yes N 5/16/2021

yes V 5/16/2021

yes M 5/17/2021
yes V 5/17/2021

yes M 5/17/2021

yes V 5/17/2021

yes M 5/17/2021

yes N 5/17/2021
yes M 5/17/2021
yes M
yes M 5/17/2021
yes V
yes 5/18/2021

yes V 5/18/2021

yes M 5/18/2021
yes N 5/18/2021
yes M 5/18/2021
yes M 5/19/2021
yes M 5/19/2021
yes M 5/19/2021
yes V 5/19/2021

yes 5/20/2021
yes M 5/21/2021

yes M 5/21/2021

yes V 5/21/2021
yes M 5/21/2021
yes M 5/21/2021

yes V 5/21/2021

yes V 5/21/2021

yes M 5/21/2021
yes V 5/21/2021
yes V 5/22/2021
yes V 4/23/2021

yes M 5/22/2021

yes M 5/22/2021

yes V 5/22/2021

yes V 5/22/2021
yes V 5/23/2021

yes V 5/23/2021

yes 5/23/2021

yes V 5/14/2021

yes V 5/25/2021

yes M 5/23/2021
yes V 7/31/2021

yes V 5/24/2021

yes V 5/25/2021

yes V 5/24/2021
yes V 5/25/2021

yes V 5/25/2021

yes M 5/25/2021

yes V 7/21/2021

yes M 7/21/2021

yes V 7/21/2021

yes M 7/21/2021
yes 7/21/2021
yes M 7/21/2021
yes M 7/21/2021
yes V 7/21/2021

yes 7/23/2021

yes 7/24/2021
yes 7/24/2021
yes 7/25/2021
yes 7/25/2021
yes V 11/7/2021
Very important 3 solutions: simple linear, tornament method and compare in pairs
This question can be done in nlogk using max Heap. We can use the technique of randomized Quickselect to get it d
Dutch National flag problem: three pointer I, j at 0 and k at length-1. cases: 0, 1 and 2. For 0 i++ & j++, for 1 j++, for 2
Simpler version of Dutch national flag problem. Use two pointer approach similar to Sort01 / partitioning approach i
There are multiple methods for this. Easiest one is using a hashmap. Other techniques include sorting both and then
sorting one and then do binary search of each item of the second array inside the first one. In the two sorting based
repeated elements. How will you handle that?

This problem has multiple solutions. The DP solution where we look at the array from right to left has a complexity o
The final optimized solution uses a Greedy approach and is O(n). Its very important to understand the Greedy appro

Hint: Floyd cycle detection approach (fast-slow),This kind of questions are very important where number rare of lim
variations for these: one number can repeat any number of times / any number can repeat any number of times / o

Difficult question: There are two methods for this- (a) Insertion methods where you swap numbers and after swapin
putting the first item in its correct position. (b) This is called the GAP method - SHELL SORT. Here we use a two point
comparing and swapping numbers and going till gap of 1 by incrementing as g = Ceil(g/2). Complexity of (a) O(n*m)

Optimal solution is O(nlogn) i.e. time to sort the array

A very good question. Do remember the pyramid concept used to find the point just smaller than next value from th
The solution is a very simple 3 step process.
1. Find number on peakIdx-1 let us call it target, here peakIdx is the index of the rightmost peak.
2. Swap target with just greater element than it (on the right side) (note: elements after target will be in descending
3. After swapping reverse numbers from peakIdx to n.

Super Tip: Same code as merge sort, just count the inversions while performing the merge operation. Another varia
Easy. Just traverse from left to right, keeping track of smallest price encuntered so far.

Three answers O(n2) simple nested loop. O(nlogn) --> sort and two pointer (handle case of repetetion). O(n) time &

Easy.

This question may be asked with following rules: (a) We need to maintain the ordering of negative and positive num
Ordering does not matter.

Optimal approach: use Prefix sum Array/HashMap. O(n) time & space. A problem of subarray can usually be solved u
(iii) sliding window, (iv) kadane's (v) DP. For (iii), there must be a clear indication when to expand and when to start
expanding and contracting (not in this case as negative numbers are there). For (iv) max/min/longest must be asked
prefix-sum approach

Use same approach as Kadane's algoritm. Do not over complicate logic. Keep it simple.
At any point in arrray, we want the max and min it can be any of the three (current value, min till prev index * curre
value )

efficient solution: use Hashmap. For each element go up and down and mark the visited elements in HM. We only d
numbers, hence complexity : O(n) time & space. Apart from this there is a simple sorting solution.

The good interview solution is the O(nk) time with O(k) space one. In case we want to present the efficient approach

Terrific question. Can be solved using (a) Dynamic Programming and (b) Divide and Conquer. Here we only look at D

Top two methods: (a) Sorting and 2 pointer (mergeing) - In case we are not allowed to use extra space. Complexity:
(b) Frequence table approach using HashMaps. Complexity: O(n) time & space
An extra loop followed by pair sum. Pls note complexity is O(n2) and not O(n2logn). Because we sort first followed b
There are 2 important approaches, one with prefix and suffix array - similar to idea of "Buying selling share at most t
array approach to 2 pointers. Watch video for 2 pointer approach [Difficult]. Remember the prefix suffix approach, i
implementation wise. For any point we need the tallest leftmost and rightmost tower.

Not a very difficult question. Concepts: Sort + find subarray of size k with min sum (sliding window) for the differenc
Can be space optimized by not creating the difference array. Best complexity O(nlongn) time and O(1) space!
This question uses concept of sliding window like the previous question.

Three pointer approach. Exact same as Dutch national flag problem (sort 0,1 & 2).

Efficient solution: Sliding window of size l. Compute ans for first window then slide right do -1 or +1 or 0 depending
element. Complexity: O(n-l) = O(n) (almost).

Think recursively. This can also be done iteratively using 2 pointers

Both these questions are similar, try to only remember the immplementation of the different sizes approach. Going
approach is to merge both the arrays and find median this requires O(n) space. It can be avoided by simply using the
count of elements encountered still the TC is O(n). The optimized approach uses BINARY SEARCH.

Easy question. Remember in this printing in four loops must happen sequentially and stop in case the prior loop doe

Easy but important question. Complexity is O(logr + logc). Please do not confuse with O(logr*logc). It will be addition
after the row is identified. We multiply when for each step within one function, another function is called, which is n

Optimization is the key for such questions. Simplest approach: O(n*m), better: O(n*logm) using Binary search, best
Question requires the use of Min Heap. Can be done in O(n2logn) time and O(n) space. Inspired by this question --->
Without min Heap we can store it in an array and sort and put back to matrix, but the space complexity increases in
This problem is different from maximum area square problem and is same as the maximum area rectangle in Histo
explaination in the video -->

A) Do simple transpose and flip. B) There is a simple approcah that uses a temp matrix of same size, but we want to
(by swapping dioganally) then reversed. Complexity: O(n2). Note: learning to inplace traspose a matrix is a pre-requ
Look at the Code written in LC 48, its very clear and easy to follow.

Same as Print elements in sorted order from row-column wise sorted matrix. Use min-Heap
These questions are similar. If we are given that the matrix is having sorted data in every row we can use a techniqu
parallel pointer approach used in merge sort), complexity: O(r*c). In case the rows are not sorted we can either sort
optimally use a HashMap to check which all elements in first row are present in all the rows, complexity: O(r*c) time

The probem is simple and generic. Given two points - the top left and bottom right, compute the sum of the sub-ma
two (inclusive). Basic approach is O(n*m) which is fine in case of one query. However, it does not scale well! Suppos
O(q*n*m). A solutuion to this is to compute an auxilary array that stores the prefix sum across rows and columns. A
O(1), though creating the auxilary array would still take O(n*m). But in case of q queries the overall time will be O(q
subsequent q queries take O(1). The aux building approach is quite straight forward. I would instead emphasise on e
GFG example very very carefully.

Easy
Easy
Easy. Note: This article states that Hashmap insert operation takes logN time with char keys, where N = size of string
Read this --->
Simple concat (i.e. a+a) and check if it contains 'b'. Complexity O(n^2) considering .contains() or .indexOf() takes O(n
the complexity of O(n) is achieved.

Easy. Its important to understand the question valid shuffle means both the string chars must come in the same ord

Can be done Recursively with base case return "1" for input=1 or iteratively like for input=1 to n (in sequence). Note
Space (O(nk) where k (max 2^n) is size of output for n-1) and time complexity analysis -->

There are certain solutions for this problem: Brute force is O(n3), using DP is O(n2) time and space also there is Expa
O(n2) time and O(1) space solution which is our main focus in this section. Finally a O(n) solution called the Manach
interviews. The Expansion approach is simple to code we have to find the 2n-1 centers (two possibilities: 1 char / 2 c

Just same as Longest Common Subsequence (LCS). We simply apply LCS on the same string itself with simple modifi
both charecters are same and the indices are different i.e. i!=j. Similar to LCS this can be optimized for space comp

Same as 78. Subsets. If we keep path as StringBuffer then the code is exactly same as 78. However, if we keep path a
backtrack step as string are immutable.

Same as 46. Permutations. Just keep path as Stringbuffer. Use the swap + backtrack idea.

Simple one traversal and keep count solution. Complexity O(n) time O(1) space.
In the recursive solution we need to try out all three operations i.e. insert, replace and delete on the first string to co
insert go (str1,str2.substring(1)), when we delete we go (str1.subtsring(1),str2) in case of replace we go (str1.substri
O(n*m) time and space and can be done both bottom-up and top down. This can be optimized in space to O(min(n,m
of the matrix and only two.

31. Next Permutation

Use single stack. Easy

Understandig the complexity of the reursive solution is also important (O(2^n)). This is an example of 1 dimensional
be further be optimized to O(n*max(d)) where n is length of string and max(d) is length of longest string in dictonary
as well.

Complex Algorithm. Difficult to understand intuition. Compute the pie array or lps array of the pattern. Meaning we
tricky part is when i != j. Watch the video from 8:15 and read code to understand the algorithm -->. Once the lps arr
pattern. We use the lps array to tack backwards in this. Intuition is that in case of a mismatch between text and pa
of the prefix. Take the example of text: "abcabcaby" and pattern: "abcaby". Once we see the mismatch at 'y' We do
char ('c') to string's ('ab') first occurance (the prefix) matches the chr in text, if it doesn't match increment i. We achi

Easy question. But do using array use ASCII. Complexity: O(n) space and O(1) time (array of size 26)

Good question, indeed. Trick approach: (a) Use stack to remove the completed brackets (b) Fault algo - simple use t
on }. In case left!=0 and } is encountered, means a pair is completed, so we decrement left as the bracket gets closed

Similar question to LPS but with a tricky recursive pattern, uses the GAP technique (2d matrix start and end - fill dia

There can be two variations for this problem: (1) Searching a word in 2-dimensional character array such that individ
characters can be present left to right, right to left, top to down or down to top (turning is allowed i.e. words can be
Searching a word that can be present in either of 8 directions (i.e. 4 diagonals, left-right-up-down). In (1) we use DFS
simple iteratively. This problem is (1). Question (2) is below

Another simple problem. Does not require recursion/DP. Difference between this and the previous is that string can
(in a line). Pro tip: use x and y array (storing directional cordinates 0,-1 and 1). Complexity: O(N*M*|word|), the sol
submission for one case (6,10..), Ignore it

Easy question. Try doing operations from back to front. If current roman char value is less than next then subtract,
A similar question is converting roman to numbers (also easy) MUST remember the 1-4-5-9 logic for roman to integ
Easy
The link question is - find second most repeated word but the question is first repeated word in a string. Both have s
Don't overthing, there is only one approach to this problem, and that is to store all words in a map.
Good question. The trick is to store the positions of '[' bracket and use them in case of an imbalance in brackets. On
an array/queue and can be optimized to use just two variables count_close and count_open and the fault count i.e
one bracket get

In the worst case we need to recursively generate all subsequences of the two strings and find the intersection. Com
O(n*m) time and space. This can be optimized in space to O(min(n,m)), since we do not need to store all rows of the

First try to think of doing it recursively. An overlapping sub-problem pattern will emerge. We can apply Dynamic pro
of possible IP addresses. Using the dp table we can compute the actual ip addresses using DFS.

Based on Minimum window substring (see row 94). Important application of slidong window

Understanding the problem is important. Here nothing about the order is mentioned. We can simply reorder in any
adjacent same chars. So, we would want to store elements with freq and put the topmost freq item then secondmo
them back again. Do this process again and again. Best DS for this is heap as it simply gives the most and second m

The objective of this question needs to be understood. It is indirectly asking to find how many characters need to b
make the string a palindrome (the chars that we can remove will be the ones we will add at start to make the string
to delete element from back and check palindrome, the complexity will be O(n2). The optimal solution would be to
the string seperated by #. And compute the lps of this string. The lps (KMP's lps and not LPS (DP)) will basically be
from the starting of the string. Subtracting this from the length of the string will be our answer. Example: str= AACE
underlined is lps (and basically the longest palindrom from start i.e. AACECAA). To make str palindrome we would eff

This is a classic problem of both (a) Hashmap and (b) Trie. Here we only talk about the Hashmap soultions. In the
(hashmap,List) maping where we store all strings associated to a particular char-count set. The complexity is O(n*
are mapped to its sorted variant (sin

Basic solution is generate all substrings and compare. Important application of Variable length sliding window appro
Generic question: smallest window in string s containing all charecters of string t. Use of 2 hashmaps and sliding win
two pointers. Complexity: O(|s|+|t|) both time and space. In case of finding smallest string containing all chars with
great video -->

There are two variants: (a) remove duplicates and keep repeating chars once and (b) remove all adjacent duplicates
recursively/iteratively in O(n). Find the simple recursive solution of (b) -->
Not as simple as it seems. Typical problem of DP. Recursive pattern is similar to LCS. Cannot be solved by two pointe
needs to be tried out and placed at multiple poistions, only 1 or a few may lead of the answer. Hence this is a recurs
For Dp approach see the video at --> 27:00. Also note the edge case for this question is unique and the dp matrix las
(taking pattern on row and string on col).

An easy question, need to be understood well. Can be done in one traversal, Complexity: O(n). Simply use an array O
a computer (Sliding window). Do note that if a customer is unable to get a computer it will leave before the custome

O(n) is aTricky solution. Compare from back, if A[a] != B[b] then a-- till they become equal (A[a] and B[b]). All the cha
added to result (They are the ones that need to be moved to front. Complexity: O(n)

Simple question. Use two arrays of size 128 each. One to map chars from A to B and other to mark if chars of B are a
and space: O(1) (constant)
Uses backtracking can be done with StringBuffer (backtracking) or simple String (Recursion) similar to letter combina

starts 28-06-2021

maximum (pivot) item is greater than its next item / minmum is smaller than its previous. Two things we need to th
reached the pivot element? (b) How do we go right or left in the array? For deciding whether to go in left or right ha
sorted or not, if it is sorted, then go to the opposite side.
Pre-requisite "find pivot in rotated sorted array"(line 105).
Uses concept of Binary search - floor & ceil
important: compare in pair method - comparisions = 3n/2 as we make 3 comparisions for every pair. Tournmanet m

Similar to find duplicate in array with numbers in range 1 to N+1, use the array itself to mark elements as -ve. See Sh
Easy problem, but the optimal solution (O(n) and O(1)) is Tricky. Some simple solutions: a) Using Hashmap/count arr
solution uses an algorithm: Moore’s Voting Algorithm. Similar to problem in row number 30
Use the technique of jumping towards right by (x-arr[i])/k indices. This will only improve the average case performa
Similar to pair sum. But pointer positioning (keep start at 0 and end at 1 index) as well as the motion of pointers is d
Similar to pair sum. But pointer positioning (keep start at 0 and end at 1 index) as well as the motion of pointers is d
Very easy problem of Dynamic programming, SC can be reduced by using two valiables = prev1 & prev2. Use concep
Optimal complexity: O(n) time and O(1) space
This question is simply an extension of "pair sum less than k", which is itself a modification of the genral pair sum pr
"pair sum less than k" -->

V important problem.Use the Shell sort approach. Note: the gap will always be ceil i.e. incremented as g/2 in case g
the initial gap should take the even odd into consideration. The tricky part in implementation is finding the array and
function for this. Complexity: O((n+m)logn+m). Same as line 17
Repeated question (see line 26). Uses Hashmaps. Technique: prefix sum
Important is to do it without divison, in this case we calculate the prefix and suffic products for all indices and use th
Complexity: O(n) and O(1). If we allow use of division. Three cases are there: no zeros, one zero or more than one ze
SC: O(1)

In case we need the numbers to be sorted by value in case set bits are equal then this problem can be done only in O
set bits (use RSB technique here). In case we don't care about the order in case of equality of set bits. Then we can j
Each array index("i") contains an arraylist of all the numbers having "i" set bits. Now our only job is to count the num
the correct bracket. This can be done in O(n*32), since for all n items we put a loop for all 32 bits. Finally, we create

This problem is very important and can be done with two approaches: (1) Insertion sort, simple insertion sort will ac
Because the inner loop in insertion sort puts the element in correct position and moves other items forward, in this
worst case). (2) Min-Heap: maintain a heap of size k+1 (i.e. Heap + Fixed length sliding window). Why? because the
position "i-k-1". so we only need to take min of next k+1 elements to fill an index i.

Very interesting problem. Think about graphs with multiple cyclic components.
Typical and Easy BS problem. Remember to compute the prefix sum array and use that to report the sum of powers
searching for optimal point using BS.
Do today
Need to do this problem without extra space. Also, take care of overlapping intervals. Its not a very difficult problem
overlapping. Watch video -->
Do today

Important one. Revise multiple times, similar to BAP, EKO, etc. Watch video-->

Flagship question usually asked when work is distributed and we want to minimize the load on participants. Note:
i.e. partition the array in k continous parts to allocate books. The array may not be sorted Firstly this can be done u
we can do it in O(nlogr) using BS. Very interesting and difficult problem. We need to understand the search space i.e
say [low,high]). Then think of going in a linear way with the criterion that:- kya hum books ko k students mai distrib
of pages a child recieves is x (do this for all x's in [low,high] and you'll get the answer)? Now can't we optimize the
linear? BS complexity: O(nlogr) where r = sum(A)-max(A). Note: isValid takes n time. Watch videos if stuck -->

Easier than the rest, uses similar approach though.


Had done this already in the DP section. Do we even need Binary search to achieve a nlogn solution for this? View m

Prior to this we need to know how to calculate number of trailing zeros in factorial, witout actually calculating the fa
this: floor(n/5) + floor(n/25) + floor(n/125)+.. Read article for more --> Now to get the smallest number with atleast
numbers from 0 to 5*n (remember the upper limit for this is 5*n and not n). Complexity: O(log2_n*log5_n)

Exact sane as Book Allocation problem (line 128)


This is a problem related to modification in Merge sort code. See line 21
We can do this in O(logn*nlogn). How? Apply simple split and mergesort recursive algorithm. While merging use the

Three way quick-sort implemented using Dutch National Flag approach. Optimal in case of multiple repeated items.

Both recursive and iterative codes are important and are O(n). Please remember the iterative code snippet as it is u

Recursive solution is simple..Doing it iteratively is very difficult! Three solutions exist: (a) Recursive - O(n) and O(n/k)

Important problem using Floyd’s Cycle detection / Turtle technique (slow - fast pointer). Remember code snippet.

There are two solutions to this problem. (a) that requires computation of length of the loop and (b) that does not.
fast (both initialized head) to intersect at a point inside the loop then we place a pointer at head and the intersectio
end and delete the conn
same as above.
Easy. Complexity: O(n) and O(1) - space and time.
Need to use a map to keep track if a number has occurred before, hence complexity: O(n) both space and time.
Very easy.
need to reverse the number and add one. Val = sum%10 and car = sum/10.
same as above, here we reverse both numbers and iteratively add.
Use two pointer technique, same as used in arrays (e.g. while merging two arrays)
read editorial, many good solutions

Again using turtle technique. Remember code snippet. Always start both slow and fast from head, for even sized list
we want to reah 1st mid element in case of even, change the while loop condition. Complexity: O(n).

The brute force approach is O(n2). There are couple of O(n) solutions to this. Solution1: Use a stack, traverse once s
along with poping the stack this time. Solution2: reverse the second half of the LL and compare with the first half, cr
individually. Note: Solution2 is the most optimal approach as it uses O(1) space complexity. Read in detail -->
Simple problem but with few important edge cases: 1. The node to be deleted is the head. 2. Node to be deleted is

Same as "Pair sum" in arrays. Please note the loop condition.


Same as "Triplet sum" in arrays
Same as k-sorted array/ nearly-sorted array problem. We can do this in O(n*k) using modified Insertion sort or O(nlo
approach, remember to add k+1 items initially and then remove (while joing them to the sorted list) and add items i

Recursive solution is simple..Doing it iteratively is very difficult!

This problem can be done by a structure that can store character while preserving the sequence as well as delete/re
Queue, Stack or Doubly Linked List or Linked List (cannot use Stack). Queeu, LL have O(1) delete from the top/head
but need to know the address. Solution using Queue would be a list of non-repeating chars till now. In case the head
need to keep track of occurances so, would use a freq array. The DLL/LL could be used as the same way as the queu
chars soon as they are repeated from the list, we can achive this using a map keeping track of the node addresses. T
simpler implementation here whereas the DLL idea is more intutive. Read the our DLL code with diagram give in Edi

There are a couple solutions of this. First of all let us assume there are N nodes (connected by next) and each node
Now merge the sub-list of head and the flattened list. This is a recursive process, with the base case megring the la
space, the total space Complexity = O(N). Solution2: Use min-heap of size N. First insert the N nodes (head of ea
bottom of removed node for all the nodes in List. TC: O(N*M*logN) (As there are total of N*M nodes in the list). Sp
number of nodes in com

Traverse the list and create three sub-LLs from the complete list for 0,1 and 2 respectively by changing the links betw
heads each for list of 0s, 1s and 2s. Just connect the three lists.
Naïve solution is straightforward. Create copy nodes for each node and map address of original nodes to copy o
explain), implementation is also not simple. This can be broken down into three steps (three seprate loops) [See o
just use the next of original node to point to the copy. NOTE: the rearrangement of random and next have to be d

Same as "Flatten a Linked List" either use Recursion or use Heap (Priority Queue).

same as sort 0,1, 2

naïve solution is to reverse the linkedlist and traverse k nodes. However the interviewer is not looking for ths solutio
pointer (say itr) on the nth node and then traverse itr along with the head pointer till itr reaches null. At this point h
NOTE: Both optimzed and Naive solution have same complexity, but the optimized one only traverses the list once.
Types of problem: i) BFS (Level Order) Traversal, ii) Iterative DFS Traversals, iii) Serialize Binary Tree & check conta
Standard solution: (a) Use Queue. Initially insert root and null. As you remove a number add its children. When null
isn't empty. Complexity: O(n) time and space. (b) Alternative solution: use pass list of list, depth to a DFS function an
(basis depth). Complexity: O(n) space and time. Solution (a) is BFS approach and is more important.
Same as above. Use a stack along with queue to print in reverse order.
V Easy
Every DFS (recursive) solution can be done in a top-down manner: passing variables / keeping global variables (the fi
computing answer of a sub-problem) or bottomup manner: assuming solution of smaller problem and creating soluti
both ways by the function returning a pair class object with both dia and height (i.e. bottomup) or computing the he
variable (i.e. topdown). This means we can simply calculate diameter while recursively calculating the height!
Easy
Recursive is simple. But please code the iterative solution once. Use only one stack. Keep pushing curr node and mo
pop, print and move curr to right (again keep pushing left till..) keep doing this process till stack not empty.
Recursive is simple. But please code the iterative solution once. Use one stack. Easiest out of the three.
repeatTill stack_not_empty(Pop from stack, push R-L children, print poped item)
Recursive is simple. But please code the iterative solution once. Need to use two stacks. Pushing order is opposite o
don't directly print it store it in st2. Once st1 gets empty sequentially print st2.

same as compute diameter. Can simply check isBalanced while recursively calculating the height! (or use the pair cla
The value of horizontal dist (x) - vertical distance (y) is same for all elements in the diagonal
Do in three parts: The left boundary (not left view) then the leaf nodes and finally the right boundary.

Great question!! This question is a combination of two. Firstly, Iterative inorder traversal (of array representing Tree
"minimum no. of swaps required to sort an array". Trick is to write the traversal (given in level order form) to inorde
"minimum no. of swaps required to sort an array" (see in searching & sorting section). Reasons: because inorder tra
BST!
Important problem. Serialization mean being able to uniquely identify a Binary tree. There are couple of ways to ser
combination of inorder and pre/post-order traversals. In this case we use technique at row 199 to deserialize it. A m
pre-order but put -1 in case of null. This requires less space. We can do the pre-order traversal simple iteratively or
deserialization code and understand it. We are using a gloabl variable t to traverse the array.

A very simple solution is to check for each node in T is S is identical to sub-tree with that node as root. Time comple
of nodes in T & S. Optimal solution: Since each Binary Tree can be uniquely identified by the combination of inorder
serialization (seaa above) we can just check if serialization of S is a subsring of serialization of T. Use KMP matching a
Serialize all the sub trees (except for the leaf nodes) and store in hashmap. If a serialized subtree string already exist

Check two conditions: (i) No cycle present in the undirected graph (can be done with simple DFS by sending parent)
same as compute diameter.
Tricky question. Need to use pair class apporach to return sum in case root is included and sum in case it is excluded
The optimal approach uses a pre-order traversal and during the traversal the running sum needs to be stored in a ha
runningsum - targetsum was encountered during the traversal or not. Once the calculation for particular node is don
hashmap and backtrack. Read: https://leetcode.com/problems/path-sum-iii/solution/ Since Hm is filled during trave

Very good problem. Read the solution code. Simplest solution: store path from root to n1 and n2 in two seprate arra
recursive approach (without extra space) IMPORTANT: Typical solution where depending on the answer by left and
contain the lca then overall lca is current root, in case either left or right says it contains the lca the overall ans is eit

Uses LCA. 1. Get the LCA node. 2. Check if its value is one of a or b.
Uses LCA. 1. get the LCA node. 2. Compute the distance between a & LCA node and b & LCA node. 3. return the sum

(i) BFS solution: for every node store its ancestors in an array, once you reach the given node make k back in the arr
Same as print all "K" sum path, keep an arraylist for the complete path (instead of the path sum) and backtrack at th
current path. (iii) Ask left and right sub-tree what ancestor number are they for the given node? Only one of L and
if currently we are at the kth ancestor (as: L+1==node or R+1==node). If not return Max(L,R)+1.

Use trick (iii) as above in combination with findBelow function.


ends 08-05-2021
During inorder traversal once we have found x, whatever node is reached next (whether we go right or in case right
above node) that is the inorder sucessor. In case we plan on using stack to to inorder traversal then its even easier t
Same code as inorder traversal (Can be done both recursively or iteratively). Just between recursive calls we make p
forward. Note initially prev is null.

See code -->

BT -> BST -> AVL(Height balanced BST). Must read Complexity analysis for search, inser
Easy

This may seem a difficult problem, but its easy if we break it down into three cases: 1. Node to be deleted is a leaf n
( i.e. return null). 2. In case it has either left or right child (child may be a sub-tree) just need to return the child nod
grandparents right/left meaning we remove the parent). 3. In case both children are there, in this case just find the
urrent node's data with this min value and recursivley call delete function to delete min from the right sub-tree (foll
>

Three cases exist: key < or > or =

All three use the concept of sending the (min,max) in arguments to recursive calls. In 1 & 3 we need to check if Tree
need to check and return T/F whereas while constructing a BST we return a node in case number lies in range else r
the parent (calling node). TC: O(n). P.S. 2 & 3 are practically same code

Keep sending (min-max) and on leaf nodes check


Very easy
A three step process. 1. Store inorder of given tree. 2. Sort it. 3. Modify node's data of existing tree in an inorder fas
Easy question. Stotr the inorder traversal and create Balanced BST from this array using recursive binary search tech

This problem can be done very easily with Auxilary space = n+m, by simply storing inorder traversals and merging bo
BST. However, the optimal solution is one that uses limited space complexity: O(height1 + height2). This one uses it
compare the numbers one by one. Whichever is smaller that is poped and added to sorted list, the right node of pop
such that we push its complete left chain - like we do in iterative inorder)

Use (reverse/normal) inorder traversal and and for the node check if count == k, keep incrementing count.

Similar to "Merge two BST" use iterative inorder (Stack) for doing the classic pair sum approach.
Use iterative inorder traversal (Stack) and keep track of prev and curr, only attach to prev.right and don't forget to m

This is again a very simple problem of inorder traversal. However till this point we only know two kinds to inorder tr
order to do this problem in O(1) space, we first need to study Morris Inorder Traversal (For Binary Tree). Very impo

Very Easy

Normal Check BST has two solutions: (i) Using passing (min-max) in argument. (ii) sub-tree to return object with isBS
modify approach(ii) i.e. The recursive call returns object with properties isBST, min, max as well as the size of tree. D
of largest size where isBST is true. Complexity: O(n)
A common mistake people do (and I did ) was sort by the window size and pick the smallest one. Instead remember
activity that finishes the first. Keep taking activities after that (whichever ones are possible). Complexity: O(nlogn) an

Not as simple as it seems. Sort by max profit, but we cannot just select the max profit jobs as they have a deadline a
the jobs in the correct slot. In case the 1 hr slot( just before deadline ) is available put it there. In case it is not - try se
couldn't find a slot for a job we skip it. Watch video --> In worst case we may have to find slot from deadline to befo
space. There is an optimal approach using Disjoint sets in O(nlogn). But we'll not study that here.

To solve this problem first watch this video completely --> In encoding part we follow that:- whichever's freq is less
editorial example for a concreate example -->. Finally the data structures w'll be using are: Heaps, Binary tree (See s
contain a charecter (we'll print once we read the node). Mostly printing in pre-order traversal is asked.
Simple Graphs - DFS problem. Important to understand what the problem is trying to ask. Look at -->

The approach for any arbitrary coin system such as {1,3,4} is using DP (Coin Change problem approach), however a s
system example: { 1, 2, 5, 10, 20, 50, 100, 500, 1000}, we can use a Greedy approach such that picking the largest de
greater than the remaining amount to be made will produce the optimal result. Such a syatem is used in US and ma
Canonical we have an algo which runs in polynomial time. Read More --> Complexities: Greedy- O(V) and DP: O(V*N

For each platform we need to apply activity selection and then add.

Here we need to count the number of schedules that can co-exist (i.e. number of separate activity selections runnin
Pick stocks at cheaper price first.
For min money spent- pick the cheapest ones and take the expensive ones as free. For the max money spent- pick th
free. Simple

Same as line 275

Good problem. The important thing to note here is that the shop is closed on Sunday. So at max a person can buy fo
that he/she must survive the 7 days. If they can survive one week then they will be able to survive more. So, we sim
if S <7 that mean's the person will never encounter a sunday, so they only need M<N (i.e. demand for the day is less
may ask the min number of times the person needs to buy, in this case remember to carry forward any amount of fo

This is exactly same as activity selection. No difference


This problem is maximum product subset, to solve it we create multiply all non-zero numbers. In case odd number o
the answer by the max negative integer. Exceptional case -a 0 0 0 0, here answer is 0. This is a simple problem unlike
extension of Kadane)

Alternate max and min items in an array and calculate the sum of abs differences of adjacent elements.
Again a very good question. Use the combination of Hashmap and DLL (similar to queue with remove from anywher
complexity. As each operation takes O(1) time and will be done at max N times. In case the queue becomes we rem
from the hashmap as well.

Very easy. Just sort and use Sliding Window.

Break the edge with larger weight first. The associated cost with each break will be (number of pieces in (perpendicu
Also if we break an edge then number of pieces in its direction will increase.

Do after revising DP

This can be done using Backtracking and without using a Stack. Since all brackets are of same kind we can simply loo
unbalanced closing ')' brackets and from the right side - counting the unbalanced opening '(' brackets. To further op
opening brackets and closing brackets that can be used for making the recursive call. We stop when o number of '('
brackets are removed. Also, both closing brackets and opening brackets are balanced in the final string. Read code t

Problem of backtracking. Try out all possible colors for a node and recur. If any recursive call is able to color all node
Cbacktracking problem, difficult. Do not try dp solution very confusion. Stick to simple backtracking.
Easy. Simple recursion. Do not overthink. Number is either included or not included.

Can be optimally done using BFS (Queue). This is a two step problem, first we compute all possible position is first a
and end points. Next we apply the shortestPathBFS algo to all poiisble start and end point pairs. The minimum of th
function is an important component of the overall solution. Note: Our solution in Coding ninjas editor is perfect. The
because of which all are not passing.

Similar to Unbounded KS. But do recursively/memoization. Have a visited matrix and add the path to ans in base cas

Easy to implement both with Array and LinkeList. Remember we can do both delete and insert with node that has an
Hence we keep the top pointer with outgoing connection to previous node. Both Array and LinkedList - push, pop o

There are three popular implementations for Queue. These are as follows: 1) Using Simple Array [ En: O(1), De:
De: O(1) ] LinkedList is more efficient than Array 3) Circular Queue (Array) [ En: O(1), De: O(1) ] -- See line 32

Easy

A very good implementation. Not possible with Array or simple LinkedList. Only possible with Doubly Linked List, m
push or pop when the count becomes odd. Why can't we use Array? Because delete from middle will ne O(n) in this
this? Though deleting middle will be O(1), updating the middle when pushing new element will not be O(1). Also, we
Overall tricky implementation

Standard, stack problem.

V Easy
The O(n) extra space solution is easier. We just have to maintain an auxilary stack to which we insert the smallest nu
this aux stack is pushed and poped , when the main stack is pushed and poped. The solution becomes very tricky w
achieve this we can only keep 1 variable (min) to keep track of min element present in the stack till the current poin
push and pop. When a number is pushed instead of pushing the original number we would push 2*curr - min (till no
item is bigger than min or smaller. If it is bigger then simply pop it and do not change the min value, in case it is sma
value as the poped value and (ii) Update the min value to 2*min - curr. In short: Any value in the stack which is < m
value was stored here and since it is poped we also need to update this value (will be a higher value than current)

Amazingly important question. Create a stack and start traversing array from back. Keep poping the stack top till you
the NGE for curr (or stack gets empty in that case NGE for curr is -1 i.e. no larger elment on right side). Remember to
as the curr element may (irrespective of its value) always be the NGE

This is an important problem, asked very commonly. Only take Operators (& brackets) to Stack. Also remeber sma
the implementation once. The postfix expression is easier for a computer to evaluate, since it does not have to care
for more -->
Easy problem. Only take operands to stack. Read best resource -->

Easy problem but the complexity will be O(n) both space and time. The recursive solution does not use any other DS
auxilary stack. See the implementation of complete class -->

This problem used the function of above problem i.e. "insert an element at bottom". Basically you remove the top, r
and then insert the element initially remoeved at the bottom. Complexity: O(n^2) time and O(n) space (recursive sta
stack is using a queue- pop all elements and simultaneously add to a queue, then remove from queue and simultan
O(n) time & space. Code for both-->

Use recursion
Easy, not a problem of Stacks or Queue. Can be done by simple sorting and merging.

First thought: A tough question indeed. Please revise the code multiple times for this question. Second thought: No
understand why we are applying NSL (variant of NGE). Basically for every item we need the index of the next smalle

Very important problem. Read all solutions on Leetcode Solution section. Optimal solution is linear time Fault algo (
both left ans and right ans. The left and right ans are only computed when count==0, here count is incremented a
bracket. Other important ones are: DP based and stack based. The Fault algo (O(1) space solution) uses the concept
brackets from both left and right. This is a very important concept and is used in other questions too like Generate m
balance and swaps to balance string

Do on 15
Easy one, remember to swap the two queues. Push: O(1), Pop: O(n)
Important: Implement deque class using DLL
Do on 15
Do on 15
Do on 15
Important question. Unlike simple array implementation where we keep front fixed at 0 here we move front forwa
is used as an indication that the stack is empty (when just rear==front, the queue is of size 1). Also, important to u
Queue is Full, i.e. when rear's next is front or when front is 0 and rear is at size-1.Must watch this short video -->

We need a Hashmap to keep track of which key is present in the cache and a Queue (that supports remove from in b
Queue needs to be implemented using DLL. The removeFromBetween will be implemented using the Node address
The DLL has interesting property of delete from between in O(1) by just knowing the address.

Easiest problem. Recursive way: Remove (from front) then recursively reverse the remaining queue. Finally add the
space (rec. stack) & time. Iterative way: empty the queue into a stack then empty the stack back into the queue. Sam
Most efficient way to reverse a queue is using a stack
Tip: Optimal way to reverse a queue is using a stack. But do we need to revrse the complete stack?
Similar to above. Use same tip. Can also be done using just an auxilary queue
Stack/Queue not required. The idea is simple, suppose we start from pump A and we were able to cross a pump (sa
again (in case we fail when starting from A). We need to start from the first pump that we couldn't reach starting fro
completing the circle is even possible or not ( difference of total petrol and distance to be covered must be > 0).

Typical multi-source BFS problem (uses queue). Idea of spreading outwards from points is used. After all the childre
Same as above, use multi-source BFS. Idea of spreding outwards from 1s to adjacent 0s is used. Note: spread out fro
Sliding window. Only negative numbers are potential answers (hence need to be added to Queue)

This is a variation of "maximum of all subarrays of size k"(line 348). Though these class of problems come under slid
"First negitive integer in every k window" this is because max/min are relative things and are not as straight forward
multiple potential answers and not just the window max/min. Also this problem uses Deque as we would need to ad
Front when number goes out of window and remove from rear when the current number is greater than existing
items). All enques are done at rear too. NOTE: All numbers are potential answers, we may deque them later.

Not a question of stack/queue/deque, instead use Heap


Use Queue, to maintain first non-repeating element (similar to first negative in every window). Keep a freq array to
queue's front
Most questions that ask first of something in a window use Queue
Create the array for next smaller element and then subtract each elment from the original array to get the answer. S

Basics

Simply apply downHeapify to all elements of array starting form the last. Complexity: O(n) - Analitically. Watch the fi
First heapify (i.e. apply downheapify to all nodes to create the heap) then remove numers one by one and store the

Various approaches to this problem, though the optimal ones use sliding window concept: (a) Use a max-heap, simp
However the complexity is O(nlogk). SLIDING WINDOW APPROACHES: (b) MONOTONIC DEQUE solution: Use a dequ
O(1)). In this methods we only keep the relevant indices (i.e. potential answers) of the window in the deque, in the f
to the rear we push the new sliding window item. Delete from the front when the window is moved and the front e
from rear make sure to remove all the indies corresponding to smaller numbers than the one we are adding. Compl
concept from next greater element's [NGE] concept (line 313), complexity: O(n) - read commnets in video for compl

Basic Heap problem, use min-Heap for k largest element and vice versa. Maintain k+1 elements in heap, remo

Simple problem, we need to find the smallest of K elements and based on that increment the pointer for one of the
to which we are standing. PriorityQueue comparator stores index of the smallest array item on top. Also, we need to
smallest element.
Same as Heapify
Same as "kth largest element in array". Create all possible subarray sums and use min-Heap to get the kth largest su
finding all subarray sums use prefix sum (Reduces complexity from (O(n3) to O(n2)). We also do not need to store th
sum and push in heap in the same loop.

Push the freq of each char in a Max-Heap. Also keep track of the previous char, in case it is same as the top of the st
char and use that in the answer. In case prev is not same as top, just use the top. Whatever we use we must decrem

Even easier than "merge K sorted arrays", uses the same concept, just put Node in the PQ

At first this seems like a very difficult problem. But if you word it in simple terms (they are writing atleast one elmen
pointers), we just need to use the same k pointer approach (as merge k sorted lists) and keep moving forward in the
k elments. Keep computing the max - min and stop when any array is completely traversed. (need to keep a variabl
seperate heap for max as we only need to check if the new elment add is > max whereas min is re-evaluated among

The most basic solution is- for each incoming integer sort the array and find median. So complexity is n * nlogn = O(
insertion sort (as it is an online sorting algo i.e. it produces sorted result at any instance)- Complexity O(n^2). Best so
maintains the max of first half and another maintains the min of the second half. We insert the incoming integer in o
greater than minHeaps smallest we put it in the minHeap otherwise it is put in the maxHeap. Once insertion is done
be either same in size or the maxHeap can be 1 greater in size. Balancing is very important and we need to take care
maxHeap OR ii) maxHeap is 2 greater than minHeap. Complexity: O(nlogn). The insert and balance functions are cal
understand -->

The best solution is using height. We need to follow two properties: HOP & CBT: For HOP we just compare the root
height of left must be equal to or 1 greater than height of right subtree. This can be implemented by a function retu
keep track of isHeap (boolean). Make post-order calls.
Typical application problem of Heaps. Easy
Since it is given in the question that the BST follows the CBT property we pnly have to take case of HOP. To do so ge
sorted min to max) traverse the BST in pre-order (I.e. node-left-right) and put the elements from the in-order array o
root and always the root is smaller than both children. read-->
lame question, no different than creating Heap from an unsorted array i.e. use downHeapify on all starting from last
Same as "reorganize strings" (line 354)
Easy- Not a question of Heap, can be done by simple sorting. 2 part question first break down number into two - usi

starts 13-06-2021

Very similar to Tree based BFS. Instead of pushing root's children we push the adjacent nodes to the queue and we
are not visited. Whichever (i) node is pushed we mark that as visited too. The code we have written in gfg will give
only (closest appearence for each node) and is using (i). Since it is possible to reach each node by multiple paths we
the node while pushing into the queue - (ii) instead mark it visited only when removing it from queue- look at Sum
calls method (ii) as r m w a : remove-mark-work-add). Don't get confused just remember you can write True in visit
different outputs. We can further modify (ii) to output each node once (only closest occurance) by checking if it is
can be used in all three BFS, Dijktra's and Prim's. Important to understand the TC: O(V+E) where V are the vertices a
expaination -->

Easy. Make use to only add in array and mark visited only once and do this before calling DFS for all children/adj nod
for children as that will happen in the recursive subproblem itself. There is only preorder and post order, nothing so

The trick is to send parent node in case of DFS and store pair object (val,parent) in queue in case of BFS. This is done
and only put/call the other node in the adjacency list. In case one of them was already visited our answer simply be

This is a tougher problem, we want to actually check the above coindition but with a catch. Since the direction is imp
previously visited node is visited again in the same depth (recursive chain), it does not form a V shape liek at 2:30 in
2 visited array. One will be same as before to check if we should make the recursive call to our child or not, and ano
current recursive chain..So as we complete the call and track back we make the visited = false in this second array. A
visited node in this second array. Watch video at --> 12:00 - 16:00. No need of PARENT here as it is Directed graph!

You can use a stack (populating a simple array from back will also work), populate it after calling on the childeren. Th
be the one that does not have any chid. And subsequent ones will be the parents.

Very important.More important than DFS, as we can modify the algorithm to solve related problems such as "min ti
Complexity : V+E.
Can be done using simple BFS (method (i), not rmwa) with/without a visited array. Since we are keeping a distance a
has been visited before or not (We may even keep pair nodes with value and distance both). The order in which BFS
from a node hence, we'll always have the shortest path between a source and target node if we start from source u

Very similar to BFS. Only important implementational difference is that we use a min Heap (with comparator on dist
object with nodes value and distance from source) instead of a simple Queue and use method modified (ii) ( r m w
removed from the Heap.. Note: As (ii) explores multiple different paths to reach every node, we always visit the min
visited the next time it comes in priority queue, we discard it.

A problem of minimum distance, I.e. shortest path. Hence use BFS


simple dfs
blem- use DFS approach. Keep a hashmap to keep track of old_node & new_node mapping. N
keep track of visited nodes and please note- in DFS always fill in the visited tracking data structure (has
Good question. Can be done using DFS or BFS!! This problem uses multiple
Father of application based questions! What is the TC?
Do a small modification in Kahn's algorithm put Int_max after pushing nodes while initializing the queue (the 0 inDe
encounter the int_max while removing nodes again push it on top - [Similar to the approach that we followed for Le
null in Queue (for printing in next line)] . TC: Same as Kahns i.e. O(V+E)
Same as Detect cycle in directed graph (use either BFS - i.e. Kahn's algo OR DFS)
Very simple
Application of count connected components on grid. Dont, be surprised if island looks at 4 directions or 8, the code
Application of Topological sort. Creating the graph is tricky (compare adjacent words to figure out an edge between

Pre-requisite: Disjoint Sets & Union Find

Aim is to keep building the tree with minimum edges. Use a BFS kind of approach for this one, since weights are invo
a) to carry the edge weight between parent and child instead of distance from the source. Min weighted edge is ta
marked visited.
Not coding question. Read Kirchoff's Graph theorem. Simple video explainations -->

Important problem. Can be solved by keeping a parent array in Bellman Ford. The first vertex in the nth cycle that is
inside the negative cycle or B) Will be after the cycle, i.e. The cycle will be reachable if we go back. In case of B we w
the cycle. Read the article or watch the video-->
A directed graph is strongly connected if there is a path between all pairs of vertices. Tarjan's algorithm is a complex
Points worth remebering: (a) Do NOT pass time in recursive call, we need it to increment for every node. Instead ke
(till head) when you find the head, do NOT always pop, this is because while checking BE/CE we only say BE if the no
return the low/disc of node (depening on BE or non-BE).

Another difficult problem, uses the concept of low and disc from Tarjan's algorithm.Basically, we traverse down and
backtrack we put the min in each node from the children (The updation of low is done similar to Tarjan's). Finally, Ar
have low[v]>disc[u], where u is parent of v. Note since the graph is undirected, we need to take care that we don't t
Hence we maintain a parent array. We also don't need a stack or isInStack, since there are no CE and all edges to alr
critical edges instead of vertices- this also uses same concept (code). I think we don't need to handle the root node c

Code is easy. Please understand why the algorithm actually works.


Can be done with small modification to BFS. i.e. r m w a algorithm
Note this is specific case of DAG. This method may only be used when it is speciifed that the Directed graph has no c
for the graph and then use the same approach of relaxing the distance array (same as Bellman Ford). Since we know
edges to the nodes before it we can follow the Topological sorted order to update the distances.

same as above

Important! Simple DFS problem

When solving a problem using DFS, we may encounter 3 secenarios: 1) We wish to find all paths from s to d in a DAG
wish to search and element in a Graph. 3) We wish to find all paths from s to d in a graph (which may have a loop). I
for both DAG and non-loop undirected (however we will need a parent argument for the non-loop undirected graph
array is required, as an element visited in one chain may not be traversed again. Case (3) is basically Rat-in-a-maze,
array, but we will backtrack (i.e. mark element False in visited) after the recursive call is complete. Why? Because w
same path/chain. TC Analysis: Case (1) & (3) are O(n^n) whereas Case (2) is O(V+E), as in the prioir two we are explo
2-Implement DFS algo, 1-Count the paths --> . This problem uses (3)

Problem of backtracking. Try out all possible colors for a node and recur. If any recursive call is able to color all node

6/27/2021
6/27/2021
6/27/2021
Needs to understand the solution, which is based on simple permutations rather than any complex BFS/DFS approa
possible permuations of triplets (3 nested loops starting i=0,j=0,k=0), i.e. nP3. For each permutation increase count
adjList for this). Finally the answer needs to be divided by 3 in case of directed graph and 6 in case of undirected. Th
and undirected. Note: in case of undirected we only consider the triange if its cyclic

Good prolem! Actually a problem of Greedy Algorithm. We try to get the person who has borrowed the highest and
owed the highest to transact money between one another by first calculating the net for each. Use 2 heaps to keep
Tricky approach. Easy solution: just complement graph and check Bipartite

Tries vs HashMap. Why use Tries at all?

Use the concept of having pc (i.e. prefix count in the TrieNode). In case the pc = 1 for the first time (while traversing
[0..m].

Whenever question of anagram is asked, things like sorting, hashmap and trie should come to the mind. In this ques
hashmap. For each word we'll insert its sorted version to the trie and at the leaf (here leaf represents the anagram's
anagram group. Note we could have also used Hashmap to store key value pair of sorted word and the correspondin
complexity. The solution with O(n*s) comlexity is discussed in Strings section. Complexity: O(nslogs) here n = numb
word. WHY? Because each word is sorted and inserted. Note since the range of words is fixed, i.e. from a to z. We ca
watch video for this sorting technique.. -->

Same as using a hashmap. The trie may be used to store strings and find unique ones. Complexity: O(r*s) this is sam
Important question, can only be done using Trie. Most questions that are prefix based shoulc be done using trie. Wa

Its important to understand the recursive solution of this problem. Read the comments in code to understand. Uses
Unbounded equivalent of the Subset Sum problem (line 433) which uses 01KS to achive similar objective. The typica
Knapsack related problems is Include (i.e. one or more): (arr[0..n],k-arr[0]) & Exclude (none): (arr[1..n],k)

Along with coin change problem this is another important problem. Please note there are three versions of Knapsac
KS, also we have fractional KS (solved using greedy). Many of the subset based problems can be solved using 01KS re
formula for 0/1 Knapsack related problems is Include: (arr[1..n],k-arr[0]) & Exclude: (arr[1..n],k)
Another easy question. Just remember the relation nCr = (n-1)C(r-1) + (n-1)Cr. We could even do a simpler recursive
Same as above just relation changes to nPr = (n-1)P(r-1) + r*(n-1)Pr. Again can be done in O(n) using direct formula s

Fairly easy question. Very similar to Fibonaci series. Can be done using (a) Recursion- Exponential Complexity, (b) Dy
1d array) (c) nCr solution basically nth Catalan number = 2nCn/(n+1). There are lot of questions that can be solved w
A very important question. The concept in this is used in multiple questions (usually related to optimization i.e. min/
it also adopts the GAP technique while filling 2d dp matrix
Moderate problem, remember the approach for every unmatched char between string we can do 3 movements. In

This problem is a re-phrasing of the original subset sum problem. The subset sum problem says: given a array/set lik
sum=5. The SS problem can be solved using the 0/1 knapsack approach, we can decide whether to include the last e
recursice formula for 0/1 Knapsack related problems is Include: (arr[0..n-1],k-arr[n]) & Exclude: (arr[0..n-1],k)

Understand the recusive function well. The last element can either combine with each of the elements before it or i
is to just find the number of combinations and not print each. It’s a simple 1-dim DP problem similar to fibonacci
Easy problem
If you understand the question (take help of the diagram) then it’s a pretty straingtforward DP problem. Easy solutio
Important recursive problem. We can create a 2d DP matrix of size: 3*(n+1). Row 0 stores the ways: last 2 fences a
ways: last 2 fences are painted the different, row 3 is for the total. Since at any point to fill the column only the pre
need to store all previous results in a matrix, we can instead just use 3 variables. Complexity: O(n). Watch -->
Cannot be done with a greedy approach, very simple 1d DP problem. Complexity: O(n). This can also be done using U

Most fundamental DP problem. Complexity: O(n*m)

Firstly, we need to understand what this question is asking: "Find the longest subsequence of character that are rep
AABEBBCDC the answer is ABBC, another eaxmple: for abcbcadbc the answer is bcbs. In short we need to compute
added condition that i!=j in case the chars at i and j of both (iteself with itself) strings are equal (We used to increme

Sometimes in recursive solutions we need to maintain a global variable (usually to keep track of max/min/count) in
may not be directly used to define the subproblem. For instance in LIS, we define the sub problem as longest increa
passed via argument). In this case we use a global variable max, which is updated for every sub problem. Such cases
programming, as DP actually stores the subproblems output in a matrix/array. Complexity: O(n2). Another way of lo
the LCS of the original array with the unique sorted version of itself, then that will be the longest increasing subsequ
all (and ony) the increasing subsequence, we just ned to find out which sequence is common between the two, that
Complexity: O(n2). Final solution: Patience sorting, Complexity: O(nlogn) - Uses Binary Searvh

Sometimes in recursive solutions we need to maintain a global variable (usually to keep track of max/min/count) in
may not be directly used to define the subproblem. For instance in LIS, we define the sub problem as longest increa
passed via argument). In this case we use a global variable max, which is updated for every sub problem. Such cases
programming, as DP actually stores the subproblems output in a matrix/array. Complexity: O(n2). Another way of lo
the LCS of the original array with the unique sorted version of itself, then that will be the longest increasing subsequ
all (and ony) the increasing subsequence, we just ned to find out which sequence is common between the two, that
Complexity: O(n2). Final solution: Patience sorting, Complexity: O(nlogn) - Uses Binary Searvh

Simply an extension of LCS. Just use a 3d dp matrix insead of 2d.


Just the same as LIS. The olnly difference is that we store the sum in the dp[i] for the max sum subsequence starting
same as Subset sum (01KS)
Another simple variation of LIS. Just change the condition when finding the max value at subsequent indices (i+1 to
Extension of Stickler Theif. Recursive relation is very important

Extension of LIS. Just change the condition in loop. Also, note that the order is not important. So, we must sort the a
applying the LIS algo. Sorting is required to to get the longest chain! This problem can be solved in O(nlogn) using a
Selection problem (in this we sort by second element)
Recursive solution: For every cell consider it as the top left corner of the square and call on the right, down and diag
DP not required for this. Very easy. Just sort and make pairs from the back
Simple DP
Use Kadane's
Not Dp, instead use greedy. Think about the condition
Variation of Rod Cutting / Unbounded Knapsack
Just try to figure out the recursive equation, we can either remove the maximum element or the minimum one. Rec
solution we'll be using the GAP technique. Complexity: O(n2) both space and time. Optimized approach: ??? Comp
This problem may be re-phrased as "longest common suffix accross all pairs of prefixs between the two strings". Exa
prefix1= ABCDH and prefix2 = AMDCDHR
Same as Coin Change problem with 3 colmumns, so the Complexity becomes O(3*n) both space and time (equivalen
Try to understand the recursive pattern. We need to find how many ways are there such that left of root can be fille
the same time right is filled with height of h-2 and such similar combos. In total we have these cases (h-1)(h-2), (h-2
can be reduced to 2 variables only. Complexity: Time O(n) and space: O(1)
Both are the same problem. In terms of DP approach both are very similar to LIS. Moving from the left we use the
compute the answer for i using that. When optimizing it we observe that we don't need to keep an array, instead j
Algorithm). Remember - Kadane's Algorithm is actually an extension of D

Understand the recursive tree first. Then think:- Why don't we use GAP technique here? Ans:- GAP technique is use
where i and j varies from start of string to the end. However in this problem all subproblems are for substrings starti
of "ilike" we call on substrings "like", "ike", "ke" and "e"only. Hence we only need a 1-dim DP array to store sub-ans
length of longest word in dict and space complexity: O(n)

A DP problem can be solved using Tabulation (more common) or Memoization. This is a typical problem of Memoiza
pattern ( sum of children / grandchildren logic) then remember to modify the tree nodes to store the computed solu

Done earlier look at Subset Sum k (line 419). Same as 0-1 Knapsack
This is just same as LPS, only difference is that we do not need to check if the substring between two same chars is
Same as "Count all palindromic substrings" (see strings section)
This can be done more efficiently without using dp matrix look in the Strings section (above). Using dp please under
question is done using the GAP startegy: We do not fill in the lower triangle and move along the diagonal. In case tw
between them is a complete palindome put 2 + dp[i+1][j-1].

This question is a modification of LIS. When looping over j = i+1 to n, use the dp[j] parity to switch the >/< equality. U
two cases the last of subsequence is > or < second last. In case it is greater than, the odd parity signifies the current
Complexity: O(n2) time and O(2*n) space. Optimally can be done in O(n) but we did not try to understand the linear

1dim DP problem. Create dp of length max(startTime) that stores max profit if we start from time i. Complexity: O(n
In such problems involving 2 player & optimal winning move, the recursive sub call (/dp array) stores whether the p
he makes the optimal move. CONCEPT --> For A (current player) to win he must make sure that all the recursive ca
will lose no matter what move it makes).
Recursive relation: (n-1)*[ count(n-2) + count(n-1) ]. Read gfg article for explaination (important). Dp implementatio
I do not consider this as a DP problem. Its more like an iterative array problem. Very important one however. In oth
to find max of BS-1([0..i]) + BS-1([i+1..n]) across all i's.

very Interesting! Similar to other Optimal move games. Here since we need to consider various sub-sets hence we u
like LPS). What is unique about it is that we try to maximize one of our two moves either take from start or the en
understand that when calling on the sub-problem our opponent will be making the move such that we have the m

Understanding the problem and its practical application: Watch video by Abdul Bari. Firstly you should know the num
given n numbers (n -sized array) a total of Cat(n) are there, where Cat represents Catalan number. Watch this video-
using a similar approach to number of possible BSTs, however in order to consider all possible subsets of the array, w
relation is quite important. What is crucial while making the recursive call is to add the corresponding freq of all the
problem to achieve the complete solution of the overall problem. It is recomended to watch the pep coding video so
Same as Matrix Chain multiplication, i.e. uses GAP traversal technique and for ever cell loops from i to j (within loop
done using 1D dp in O(n2) by thinking of a recursive solution consisting of palindrome prefix and associated sub-pro

Think of recursive pattern first then dynamic solution first. Observe the repeating sub-problems. The DP solution use
Simple problem, loops towards right from every index while computing the value for that particular index. Complexi
extra spaces are squared and added we need to apply a DP approach, if it was simply added, every configration wou
gfg editorial its confusing..

Pre-requisites: (a) Submatrix Sum Queries (pre-computed auxilary array approach), (b) Kadane's Algorithm. Note: W
and not the complete au array when using (a). This problem is an extension of Kadane's algorithm to 2d array/matr
How? 1. Try out all sub-matrices - 4 nested loops. 2. For each sub-matrix compute the sum.Optimal solution is O(r2*
Kadane is key to reduction in complexity! Must read code on GFG written by us.

Exactly same as "Largest rectangular sub-matrix whose sum is 0"


Uses exact same approach as "Maximum sum rectangle in 2D matrix" (Pre-requisite). Except it uses longest length s
loop, instead of maximum sum sub-array. The final ans is the largest area amoung each submatrix. This is computed
the submatrix.
2-dim DP problem. Simple DP solution O(n2 * k) traverse from right to left in each cell we store the maximum profit
column to the end, doing at most i transactions. j ranges (0,n) and i ranges(0,k). In this solution we'll have to look all
current cell ([i+1][j+1 to n]), hence the complexity is O(n*k*n). There is a trick in the question, to do the forward lo
overall complexity to O(n*k). Read the code to understand that.

Tricky question, very important to undertand the problem. We can NOT use simple two pointer (Merge) approach in
the video -->. Overall DP approach similar to LCS (i.e. uses 2d matrix and each cell represents pairs between substrin
Remember the char from s1 or s2 is compared to (i+j)th index in s3. Also important What is the base case & how y
When using the LIS approach do not forget to sort!! Otherwise Activity selection algo (Greedy) is optimal)

Basics of how numbers are stored, All basic operators


Can be done in O(1) using formula rsb_mask = x & (~x+1). The simple method is O(number of total bits) / O(logn) an
till non-zero product is found

Simple solution: Complexity = number of bits (32). Use a mask and shift it left till it is 0, increment ctr for non-zero m
Algorithm. Idea is to subtract the RSB from n and keep doing this till number becomes 0. Complexity = number of se
bits set, both approaches take same time. But for any other scenario Kernighan's is more efficient. Watch video -->

Basically we need to segregate the array elements into two groups and then do the {unique in duplicates} seperatel
be made such that both unique numbers lie in different groups. How do we do this? We take help of the xor of all el
actually be the xor of the two unique numbers. Use this xorAll to compute the mask (any set bit, lets say the RSB of

Easy, count the set bits in {a XOR b}, (Can use Kernighan's algo for optimization)
A recursive solution is possible. Watch video -->
The trick method is to see if n&(n-1) == 0. In case a number is a power of 2, it will only have 1 set bit and (n-1) will h
set. Effectively the & of n and (n-1) will be zero. Make sure to handle the case of n=0 as answer for this is false. COm
Simple first check if number is power of 2. If yes then use mask to calculate the distance or simply return log(n)/log(
Simple create a mask from y using a loop. Finally | it with x. Can you do this without a loop? Watch video to see trick

A tricky problem. There are two ways to compute division. First is the simple way which says keep subtracting the n
times we subtract before reaching a number < dividend is our quotient.This has a complexity of n/divisor or in wors
The second approach is by subtracting the divisor from n and again subtracting divisor after doubling it, then quadru
find the largest number * 2^x that we can subtract from the dividend. We repeat this process by replacing the divid
the (non-zero) difference is smaller than the actual divisor (in this case the difference may be regarded as the remai
we add to the answer 2^count. Note: Complexity of this approach is O(logn) ( even in case divisor = 1). Best video e
using long instead of int to handle the overflow case (i.e. dividend = Integer.MIN_VALUE)

Tricky problem same as above. We multiply n with 2^x till this multiplication factor is < the required factor ( which is
after each iteration we requce the required factor. Read code ->
from low (2^(size-1)) to high [2^(size-1)-1] we generate a string for all numbers by traversing the binary representati
Important problem. Concept used is that whenever for a subarray the xorAll = 0, means we can split it into to at any
will be the same. Using this concept this problem can be solved in O(n2) instead of O(n3). Watch -->
Important to break number into four cases: 4x, 4x+1,4x+2,4x+3. Forms a and c are basically even and can only be so
by getting the number to be a multiple of 4. Therefor we add 1 in case d and subtract 1 in case b to get to 4x and 4x+
Important to handle case of overflows.
https://www.youtube.com/watch?v=txd3UKiSD5Q&t=6s
https://www.youtube.com/watch?v=hGK_5n81drs
https://www.baeldung.com/java-sorting-arrays-with-repeated-entries

https://www.geeksforgeeks.org/find-union-and-intersection-of-two-unsorted-arrays/

https://www.geeksforgeeks.org/minimum-number-jumps-reach-endset-2on-solution/

https://www.youtube.com/watch?v=dfIqLxAf-8s

https://www.youtube.com/watch?v=hVl2b3bLzBw

https://www.youtube.com/watch?v=LuLCLgMElus

Reverse Pair
Multiple variations are there for this problem. Do solve

In case (a) there may ne O(n) solution with O(n) additional space. But solving in O(1) space can
only be done in O(n2) time, which uses a array rotation approach.
In case (b) wee can simply take all positives to left and negatives to right and then do
rearrangement by swapping.

https://www.youtube.com/watch?v=0d35oJyEous&t=609s

a HM. Very similar to Majority element, however optimal solutioin uses HM.

https://www.youtube.com/watch?v=37s1_xBiqH0

on O(nlogn+n*n) = O(n2).

https://www.youtube.com/watch?v=m18Hntz4go8&t=209s
However, following (-->) do not use concept of sliding window, since they have negative
elements, we use HashMap. Print / Count of sub arrays with sum equal to K with negative
values.
& Smallest sub array with sum equal to K with negative values.

We need to partition first array such that smaller elements of both arrays are on left and greater
ones are on right such that this condition is met: l1 < r1 and l2 < r2. Here l1, l2 are largest
elements of arr1 and arr2 which are on the left of partition and r1, r2 are smallest ones of arr1
and arr2 on the right partition. Apply binary search with lo = 0 and hi = n1 on the first array. Note
we are partitioning only array1. Array2 is automatically partitioned. The answer is
max(l1,l2)+min(r1,r2)/2 when n1+n2 is even, if odd the ans is min(r1,r2). Best explain ----->

merge k sorted array

https://www.youtube.com/watch?v=dAVF2NpC3j4

https://www.geeksforgeeks.org/rotate-matrix-90-degree-without-using-extra-space-set-2/
Another good source to read

https://www.baeldung.com/java-string-immutable

https://www.youtube.com/watch?v=qN_vwYtvFUM

https://leetcode.com/problems/count-and-say/discuss/248980/Java-Solution

Check out video for recursive solution

https://www.geeksforgeeks.org/print-subsequences-string-iterative-method/
https://www.geeksforgeeks.org/edit-distance-dp-5/

LeetCode question

Simple recursive and DP approach explained

the length of longest lps from pattern[0..i]. To compute this use two pointer approach with i=0 and j=1,
matching this is also very similar to the lps computation, its just done with two strings now the text and
g back all the way in the text string we can simply use the lps array to check if it matches the next element
instead we can use the lps array to check if the suffix 'ab' had come earlier and if yes than check if the next
this. Since we traverse the text string only once and the pattern string once (to compute the lps array).

Length of longest substring of brackets

pep coding video

https://practice.geeksforgeeks.org/problems/convert-to-roman-no/1
p the brackets and add j-I to the ans (where j and I are opening and closing bracket positions). This requires
ase we encounter a opening bracket we add the fault value to the answer and decrement the fault by 1 (as
ation -->

See the simple DP bottom up solution here from 25:00

https://www.youtube.com/watch?v=e1HlptlipB0

Note: Any question requireing the computation of longest palindrom from starting
of string can use this methods of concat and LPS computation. Complexity is only O(n). (Actually
O(2*n+1). Read more -->

hMap of HashMap. The inner hashmap is created for each word and is a (char,int) Hm. The outer map is a
versing each char. In simpler solutions instead of this we can simply use a map of strings. Where all strings
nd are equal in sorted form)

https://www.youtube.com/watch?v=e1HlptlipB0
https://www.youtube.com/watch?v=NbgUZAoIz3g

Pro tip: if this question was "we can only move chars to back of the string"then we would have
compared from front

visualizer: https://algorithm-visualizer.org/greedy/boyermoores-majority-vote

y remains O(n)
nt of unique pairs
nt of unique pairs

https://www.geeksforgeeks.org/count-pairs-array-whose-sum-less-x/
Watch from 4:15

https://www.youtube.com/watch?v=wSOfYesTBRk&t=990s

https://www.youtube.com/watch?v=gYmWHvRHu-s&t=281s

https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/1322732/Single-loop-solution-O(nlogn)-
ed in line 17. This merge operation takes nlogn time, instead of the simple merge with two arrays taking n time.

Imp Question:When does the worst case of Quicksort occur?

Java objs in memory: Node variables store the address of Node object which is allocated on Heap

... (c) iterative without extra space - O(n) and O(1)

itorial on GFG, note its important to remember the derivation of (b). Basically in (b) we are using slow and
together with the same speed. They meet at the start of loop, once we reach here its very simple reach the
- space and time

https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
e node in list and that is to be deleted.

https://www.youtube.com/watch?v=tJK7vjNKdLY

DLL approach

y bottom). The max size sub-list is of size M. Now, solution1: flatten the list starting from next of the head.
y (worst-case: all sublists of size M) = 2M+3M+4M+...NM = O(N^2*M) time and considering recursive stack
nimum and simultaneously add its bottom node. Repeat this step removing the top-most and adding the
te in GFG editorial solution complexites are O(N*M) and O(N*logN) respectively since N there means total
our expaination).

Note: Edge cases like 0000, 0202220, 1010001, 2221212, etc are important. NOTE: We do not use any additional spa

e>. Complxity: O(n) time and space. Optimal solution: Very difficult !! Approach is tricky (and difficult to
ttach copy nodes to the original ones and rearrange the next and random pointers. Instead of using a map,
randoms for each coppied node then map their next and simultaneously reset the next of original nodes.

Edge cases: k > n & k = n


Solution (a) code

https://www.youtube.com/watch?v=5y_j0OqD7v8

https://www.youtube.com/watch?v=K2ybI-GEHSY&t=74s

https://www.youtube.com/watch?v=k21VKEM8OFY

Read code written by me in codestudio (CN editor)


https://www.youtube.com/watch?v=Se7y4Nl0cCM

https://www.youtube.com/watch?v=uZzvivFkgtM&t=326s

Backtracking + path sum / prefix sum (Hashmap)

https://www.youtube.com/watch?v=cZ0OhoxwaJ8&list=PLNxqWc8Uj2LRbsOlBiPJZAyZpaUwdDepd&index=29

Read: https://leetcode.com/problems/path-sum-iii/solution/

Advantage of BST over Hashmap


https://www.youtube.com/watch?v=5_AZcOOc-kM

https://www.geeksforgeeks.org/merge-two-bsts-with-limited-extra-space/

Morris Traversal
Watch from 5:20

https://www.youtube.com/watch?v=vt_Z6tdV81Q

See at 14:00

https://en.wikipedia.org/wiki/Change-making_problem

Both use the concept of Activity selection. Sort by Finish time / Departure time and then apply
selection logic.
`

https://www.youtube.com/watch?v=u23ROrlSK_g

https://www.youtube.com/watch?v=Cbbf5qe5stw&t=1078s
2) Using LinkedList
(a) Solution using Auxilary stack

https://www.youtube.com/watch?v=sDKpIO2HGq0

https://runestone.academy/runestone/books/published/pythonds/Bas

https://www.youtube.com/watch?v=vcv3REtIvEo
Great Explaination

e increment the marker.

Array representation, Insert, Delete, Heapify & HeapSort

Further read: Why Down Heapify is used instead of Up Heapify for creating a heap? How is it O(n) - Analytically
y = n + nlogn. Overall O(nlogn)

Approach(c) NGE based

https://www.youtube.com/watch?v=Fqal25ZgEDo

https://www.youtube.com/watch?v=EcNbRjEcb14&t=792s
https://www.geeksforgeeks.org/convert-bst-min-heap/

he two strings using carry

https://stackoverflow.com/questions/26549140/breadth-first-search-time-complexity-analysis

https://www.youtube.com/watch?v=uzVUw90ZFIg&list=PLgUwDviBIf0rGEWe64KWas0Nryn7SCRWw&index=12

Topological sort is usually used in problems that have dependency of one job/file on another,
so example if the nodes in graphs are jobs that depend on on another than the revese order of
toplogical sort is the way we have to proceed (order of jobs done) such that all jobs can be done.

https://www.youtube.com/watch?v=tggiFvaxjrY
https://www.geeksforgeeks.org/shortest-path-unweighted-graph/

Why use Dijkstra's (i.e. Priority Queue) for weighted graph and not simple BFS ( i.e. Queue) for shortest path in weig

sited array, just use the


cases) before making the recursive call.

What is a tree? A Trees inside a graph is an acyclic sub-graph with all connected nodes. All
vertices may not be covered
What is spanning tree? spanning inside a graph is a tree with all vertices of the graph
What is MST? Minimum spanning tree is a spanning tree inside the graph with minimum sum
path
If the given graph has V vertices then a spanning tree will have V-1 edges.

https://www.youtube.com/watch?v=Vw-sktU1zmc&t=199s

https://www.youtube.com/watch?v=HlcpVDCAZFM
https://cp-algorithms.com/graph/bellman_ford.html

https://cp-algorithms.com/graph/bellman_ford.html
https://www.youtube.com/watch?v=ZeDNSeilf-Y

https://www.youtube.com/watch?v=64KK9K4RpKE

Both Tarjan's and Kosaraju's are for Directed graphs, for undirected ones simply use DFS/BFS

Its important to note that in this problem we are given a graph (which may have loops) in case it
was a DAG, we would have instead used "Longest path in DAG approach"
TST: A space efficient alternate to Tries (used in Autocomplete and Spell check)

Hashmap vs Trie: to search word

https://www.youtube.com/watch?v=DfkLGiW8vNA&t=461s

Both use concept of 0-1 (reject-select) recusion to generate the sub-problems. However Coin
change uses unbounded (i,e, 0, 1 or more).

Cr = (n/r)*(n-1)C(r-1)

Read this article for better understanding of solutions Note: We need to use BigInteger for n>80
Questions using same concept-->

gonal movement.

original- Subset Sum problem (SS)

https://www.youtube.com/watch?v=ju8vrEAsa3Q&t=577s

For O(n2) solution watch this (IMPORTANT)


Video - Amazing explaination See at 14:00 to 40:00

https://www.youtube.com/watch?v=FO7VXDfS8Gk

Read this article

ng the GAP technique only.


Check out vide for recursive solution

ay traversal overall O(nlogn) & space: O(n)

https://www.youtube.com/watch?v=wuzTpONbd-0

Video by Abdul bari to understand the problem, meaning of freq array and its relavance in optimal searching

Video for both solutions

https://leetcode.com/problems/text-justification/
Watch this video (please note our implementation is litte different. We traverse from right to left in matrix)

Watch complete video

Two's complement

https://www.youtube.com/watch?v=XcSr6TIMl7w

https://www.youtube.com/watch?v=I475waWiTK4

https://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-array-of-repeating-elements/

https://www.youtube.com/watch?v=g6OxU-hRGtY&t=72s

https://www.youtube.com/watch?v=v7pUZw-ZOYU

https://www.youtube.com/watch?v=m4L_5qG4vG8&t=12s

nthing for 000.

https://www.youtube.com/watch?v=sdJBPdoD3OY&list=PL-Jc9J83PIiFJRioti3ZV7QabwoJK6eKe&index=11
https://www.youtube.com/watch?v=pW5fvwnZ1TA&list=PL-Jc9J83PIiFJRioti3ZV7QabwoJK6eKe&index=12
start watching at 10:00 for quickselect

https://www.youtube.com/watch?v=vBdo7wtwlXs

https://www.tutorialspoint.com/data_structures_algorithms/shell_sort_algorithm.htm

We need to know the use of comparator/comparable


to sort this type of array and solve this problem. Especially -> comparators in java 8
Variation: print subarray with sum 0

Note the D&C technique is more intuitive. We fill two arrays, first from left to right, each index having
max profit when buying-selling is allowed till that point. And the second array filled from right to left,
each index having max profit when buying-selling allowed from that point to the end. Finally our objective
is to find the "i" which maximizes first[i-1] and second[i].

Main objective is that each index in array can store water when there exists walls larger than itself on
both left and right. And the amount it can store is min(left,right) - arr[i].
(1b) Any sub array / # of sub array / smallest sub array with sum equal to K with non-negative values.

https://www.youtube.com/watch?v=yD7wV8SyPrc&t=1230s
Note: Concatinating while looping a string is expensive (creates and new string everytime since strings are immutab

https://stackoverflow.com/questions/43624822/what-is-the-space-complexity-of-my-recursive-solution-for-count-a

Check out video for DP solution


Leetcode Code Link

My approach with low complexity here

https://www.youtube.com/watch?v=ziteu2FpYsA

Alternate question: count all distinct palandromic subsequences


https://www.youtube.com/watch?v=Ylz6mwghDrU

See top down DP approach here

https://www.geeksforgeeks.org/minimum-characters-added-front-make-string-palindrome/

https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together/
Similar question but we can move chars to both back or front (uses LCS)

https://www.youtube.com/watch?v=vF7gk4iaklA&list=TLGGwHepYQDkaX4wNDA3MjAyMQ&t=1s

https://www.youtube.com/watch?v=n5QY3x_GNDg

https://www.youtube.com/watch?v=XGrXiVi7Ces
ingle-loop-solution-O(nlogn)-without-Binary-Search
taking n time.

Imp Implementation: Can QuickSort be implemented in O(nLogn) worst case time complexity?

d on Heap

https://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/
Queue based approach

Solution2: GFG

do not use any additional space!

https://www.youtube.com/watch?v=VNf6VynfpdM
Solutiob (b) code
https://www.geeksforgeeks.org/serialize-deserialize-binary-tree/

https://www.youtube.com/watch?v=uZzvivFkgtM

https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/
My code for Morris Traversal
https://www.geeksforgeeks.org/huffman-coding-greedy-algo-3/
(b) O(1) space trick

Variants: NSL, NSR, NGL, NGR ( also called NGE)

ooks/published/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
Heapify

w is it O(n) - Analytically
Approach (b) See the image

leetcode
https://www.youtube.com/watch?v=UeE67iCK2lQ&list=PLgUwDviBIf0rGEWe64KWas0Nryn7SCRWw&index=6

0Nryn7SCRWw&index=12
Best Explaination video

Watch from 9:00


Example of (1)
Benchmark: Genrally Hashmaps are faster in terms of insertion and read/search time, whereas Tries are more mem

Let us say we have only 'd' coins allowed, then how do we solve this? -->

In 01KS, is you include the item then you do not consider it in the recursiive call ( whereas in Coin change
even if you consider the coin, in the recursive call you allow the same coin again (as you have unlimited
supply)

Catalan number important questions


Palandromic Partition with minimum cuts (see row 461)

https://www.youtube.com/watch?v=34l1kTIQCIA

For LCS based solution read this


Code here -->
Check out video for DP solution

pep coding solution video, Watch starting 20:00

Watch video for the approach - starting 6:00


ight to left in matrix)

0 -> 7 -> -8 -> -1 . Remember Integer.MAX_VALUE + 1 = Integer.MIN_VALUE

ating-elements/

oJK6eKe&index=11
woJK6eKe&index=12
GFG random Quickselect link

https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/
https://mkyong.com/java8/java-8-lambda-comparator-example/
Comparator to sort 2d array for java 6,7 & 8
if(arr[j]>=0) {
HashMap<>(
);
longint temp int
=maxProduct(
sum arr[j];
= 0;
int[] arr, int
n) { arr[j++]
for(int
= arr[i];
i=0;i<n;i++) {
// code
sum
class+=
here arr[i++]
=Solution
arr[i]; temp;long{
minSA public = int
}else
if(sum
arr[0];
maxProfit(in { == 0)
{t[] prices) long {
maxSA j++;=n =
int
arr[0];
prices.lengt
}printFromTo
h; long
(-1, i,int[]
globalMax arr);} =
arr[0];
firstBS =
for(int
}new int[n];
k=0;k<arr.lefor(int
int[]
ngth;k++)
if(hm.contai
i=1;i<n;i++){
secBS = new {
nsKey(sum))
int[n]; long
if(arr[k]<0)
{
minTemp =
{negStart
minSA*arr[i]int min =
k; break;}
;= prices[0];for(int
item:intlong }
max
hm.get(sum)
maxTemp
= prices[n- i ==
0;
)1]; {
maxSA*arr[i
];
for(int
while(arr[i]>
printFromTo
minSA
i=1;i<n;i++){ =
0 &&
(Math.min(it
Math.min(M
negStart<arr
em,i),Math.
ath.min(arr[i
firstBS[i] =
.length)
max(item,i),
],minTemp),
Math.max(fi {
arr);
maxTemp);
rstBS[i-
int temp = -
1],prices[i]
arr[i];
min);} =
maxSA
Math.max(
arr[i]
Math.max(a
if(prices[i]<=
arr[negStart]
ArrayList<Int
rr[i],minTem
min) min =
;p),maxTemp
eger>
prices[i]; bList =
hm.get(sum)
); }
arr[negStart
;
++] =for(int
globalMax temp;=
Math.max(gl
i=n-
i+=2;
bList.add(i);
obalMax,ma
2;i>=0;i--){
xSA); }
}
secBS[i] =
}
hm.put(sum,
Math.max(s
bList);
globalMax
ecBS[i+1],m=
Math.max(gl
ax -
}prices[i]);
obalMax,ma
xSA);
else {
return
if(prices[i]>
globalMax;
max) max =
}
prices[i];
ArrayList<Int
}
eger> aList =
new int ans =
ArrayList<Int
0 + secBS[0];
eger>();
for(int
i=1;i<prices.l
aList.add(i);
ength;i++){
ans =
while(i<j) {

if(arr[i]==arr
[j]) {

i++;
Why can't we use the same techniques in case negatives numbers are there?-> Because it does not satisfy the criter
j--;

}else
if(arr[i]<arr[j
]) {

//
change the
next
element to
sum of
current and
itself

arr[i+1]
= arr[i]
+arr[i+1];

i++;

ans++;

}else {

//
change the
previous
element to
sum of
current and
itself

arr[j-1]
= arr[j]
+arr[j-1];

j--;

ans++;

}
}
//
inp :
{1,4,8,11,5}
--> (the final
array is
meaning
less but we
get the
number of
minimum
//
operations
required
correctly)
{1,5,8,19,5},
answer --> 2
eqRecursive(
}
String str,
String
// nowpath, we
int
private int
have start,
the
end){
row
staticwith
min
boolean pointer
if(start>end)
value
isValidShuffl
{e(String str1,
//
String str2,
System.out.
decrement
String res) {
println(path)
all other
;arr[i]s other int
than
l1 = this
return;
index
str1.length()
; }
int
printAllSubs
int
l2 =flag = 0;
eqRecursive(
str2.length()
str,
for(int
;
path,start+1
i=0;i<r;i++) int {l
,end);
= private static boolean isRotationString(String
res.length(); if(i! str1, String str2) {
printAllSubs
=minRowInd // Complexity: substring() --> O(1)
eqRecursive(
x && mat[i] int // Overall: for N characters each iteration
str,
[arr[i]]>mat[
i=0; path + takes O(N) time so total O(N2)
private
str.charAt(st
minRowIndx int for(int i=str1.length()-1;i>=0;i--) {
static
]j=0; void
art),
split01Equall
start+1,end)
[arr[minRow int if(str2.equals(str1.substring(i,str1.length()) +
y(String
;Indx]])
k=0; str) str1.substring(0,i))) return true;
{ arr[i]--; } flag }
int n
=https://interviews.school/strings
1;
while(k<l) { } return false;
=private }
str.length();
static
}// either voidthe
printAllSubs
char is from int private static boolean isRotationConcat(String
cnt =
eqIter(String
string1 or 0; str1, String str2) {
str)
//
string2 else{
flag = int
0 // Complexity: O(n)
start
-solution-for-count-and-say
means
false = 0;int
all n String str = str1.concat(str2);
=the items if(str.indexOf(str2)!=-1) return true;
StringBuilde
str.length();
were
if(i<l1 && return false;
rpointer
sb =
str1.charAt(i new int
was }
StringBuilde
num
pointing
)==res.charA = (int)
to
r();
Math.pow(2
(in each
t(k)) i++;
,row) n) - 1;were
equal
else if(j<l2
for(int
&&
i=0;i<n;i++)
// so we {
str2.charAt(j
for(int
print
)==res.charAthe
if(str.charAt(
i=0;i<=num;i
item
t(k)) j++; and
i)=='0')
++)
decriment{ cnt+
+;
all pointers
else return
StringBuilde
false;
else cnt--;
rif(flag==0)
substr = {
new
k++;
StringBuilde }
if(cnt==0)
r();
System.out. //{
println(mat[
true if both
for(int cntare
minRowIndx
strings = 0;
j=0;j<n;j++)
]completely {
[arr[minRow
traversed
sb.append(s
else //
Indx]]); check
false
tr.substring(
if jth bit in i
start,i+1));
is set(i.e.
return for(int1).
i=0;i<r;i++)
i==l1&&j==l
// if it is
{2;arr[i]--;}
sb.append("
set then }
");
print
} jth
col, int
row_max,
int col_max,
int
needle_pt) {

if(needle_pt
==needle.le
ngth())
return 1;

if(row<0 ||
row>row_m
ax || col<0
||
col>col_max
) return 0;
Note:
if(needle.ch complexity of
arAt(needle substring
_pt)! function is
=str[row].ch O(length of
Important to understand the complexity of simple recursive solution
arAt(col)) substring). Do
return 0; consider that
as well while
int looking at
ans = solution.
internalSear
ch(needle,st
r,row-
1,col,row_m
ax,col_max,
needle_pt+1
)

+
internalSear
ch(needle,st
r,row,col+1,r
ow_max,col
_max,needle
_pt+1)

+
internalSear
ch(needle,st
r,row+1,col,r
ow_max,col
_max,needle
_pt+1)

+
internalSear
ch(needle,st
r,row,col-
1,row_max,c
ol_max,nee
dle_pt+1);

//System.ou
t.println(ans
+""
+needle);

return ans;
}
gth();

int dp[]
[] = new
int[2][n2+1];
int bi =
0;
for(int
i=n1-
1;i>=0;i--){

bi = i
%2==0? 0 :
1;
<-- Space optimized DP solution
for(int j=n2-
1;j>=0;j--){

if(text1.char
At(i)==text2.
charAt(j)){

dp[bi][j] = 1
+ dp[1-bi]
[j+1];
}els
e{
private
dp[bi][j] =
static void
Math.max(d
removeAdjH
p[1-bi]
elper(String
[j],dp[bi]
str, int curr,
[j+1]);
char prev,}
StringBuilde
}
r sb)}{
return
if(curr==str.l
dp[bi][0];
ength())
}
return;
}
char current
=
str.charAt(c
urr);

if((curr+1==s
tr.length()
|| current!
=str.charAt(c
urr+1)) &&
current!
=prev) {

sb.append(c <--(b)
urrent);
}

removeAdjH
elper(str,
curr+1,
current, sb);
}
private
[] wordLists,
isAnagram(s
not
int using
tr1,
computer str2))
listNo
return,String -1;
Builder int
path) //{ we
s1
need = to
str1.length()
check if
if(listNo==w
-1;
available
ordLists.leng int
th)
s2 = if(ctr<n)
{str2.length()
System.out
{.println(path
-1;static int
.toString()); int
square_root
return;} //
ans
(int = 0;
N) { ch
available.
can // code
sit!
for(String
while(s1>=0)
here
word:
{ if(N==1)
wordLists[lis
return
arr[ch-'A']
tNo]) { 0; =
while(s1>=0
true;long
&&
start = 0;
StringBuilde
str1.charAt(s
r1)! long
newPath ctr+
=
end
+;
new = N/2;
=str2.charAt
StringBuilde
(s2)) {
while(start<
r(path); }else {
=end){
ans++;
long
//
newPath.ap
mid
not = start
available
pend(word); +
(end s1--;
-
start)/2;
newPath.ap
}// as we
if(reject[ch-'
pend("
exit ");
A']) {this loop
//System.ou
str1[s1] will
t.println(mid
printAllSent
be equal to
);
Help(wordLi
str2[s2]
// if it is
sts,listNo+1,
if(mid*mid<
waiting
newPath);
s1--;
(long)N){
don't need }
to update} //
s2--;
means
answer ans
private}
lies
since on
static voidis
ansright
already
printAllSent(
return= ans;
start
incremented mid +
String[][]
1;
wordLists) {
}else
if(mid*mid>
reject[ch-'A']
printAllSent
(long)N){
=Help(wordLi
false; //
bye
sts, 0and ,new //
means
sorry
StringBuilde ans
lies
r()); on left
} end
=}else
mid {- 1;
}else
return
(int)mid;
reject[ch-'A']
= true;} //
wait return
(int)(start-
1);
ans++; // ofc
} not
it will
get a
computer

}
if(arr[i]-
prevC>=mid)
{

prevC =
arr[i];

remainC--;

if(remainC=
=0) break;

//
System.out.
println(mid
+":"+remain
C);

if(remainC>
0){

high =
mid - 1;

}else
if(remainC
== 0){

largetMid =
mid;

low =
mid + 1;

}
}

System.out.
println(large
tMid);
}
public
static void
main
(String[]
args) throws
java.lang.Exc
eption{

BufferedRea
der br = new
BufferedRea
der(new
InputStream
Reader(Syst
em.in));
int t =
Integer.pars
Node temp
low,high);
= head.next;
quickSort(ar
head.next =
r,low,pivot.s
null;
tart-1);
Node
quickSort(ar
newHead
r,pivot.end+ =
reverseList(t
1,high);
emp);}
static pair
temp.next
partition(int=
head;public
arr[], int
static
low, int
return
boolean
high){
newHead;
detectLoop(
int
Node }
i=low;head){
Node
int
j=low;=Node
slow head;
reverseList(
Node
int
Node
fast = head)
k=high-1; head;
{
while(fast!
while(j<=k){ //
code
=null && here
fast.next!
if(arr[j]<arr[
if(head==nul
=null){
high]){
l) return slow
int
null;
=tempslow.next;
=
arr[i]; fast =
if(head.next
fast.next.ne
==null)
xt;
arr[i++] =
return
arr[j]; head;
if(fast==slow
Node
)arr[j++]
returnprev
= =
null;
true;
temp;
} }else
Node curr =
return
if(arr[j]>arr[
head;
false;
high]){
} int
Node
temp =after =
head.next;
arr[k];

arr[k--] =
while(curr!
arr[j];
=null){
arr[j] =
curr.next
temp; =
prev; }else{
//
prev
equal= curr;
j++;
curr = after;
}
}
if(after!
int
=null)
temp =after =
after.next;
arr[high];
}
arr[high] =
arr[j];
return prev;
arr[j] =
temp; }
return
new pair(i,j);
}
}
DLL approach video

Solution1: Striver's
Pleasevideo
note (Complexity
that mergingexplained
linked lists
is does
wrongnot
look
take
at extra
pinnedspace
comment)
(unlike arrays). We can simple rearrang
private int
ans = -1;
private int
prev = -1;
private
void
inorder(Tree
Node root,
int node){

if(root==null
) return;
int curr
= root.val;

if(node==cur
r){
ans =
prev;
}
prev =
curr;

inorder(root
.left,node);

inorder(root
.right,node);
}
public
List<Integer
>
high) {

if(curr>=arr.l
ength)
return;

if(arr[curr]>
=low &&
arr[curr]<=hi
gh) {

int prev =
curr;

curr++;

CheckPreIsB
STHelper(arr
,low,arr[pre
v]-1);

CheckPreIsB
STHelper(arr
,arr[prev]
+1,high);
}
}
private
static
boolean
CheckPreIsB
ST(int[] arr) {
//
Function
checks if a
given array
is a valid
preorder
traversal of
a BST?

curr = 0;

CheckPreIsB
STHelper(arr
,Integer.MIN
_VALUE,Inte
ger.MAX_VA
LUE);

return
curr>=arr.le
ngth;
}
ist<Integer>
> hm = new
HashMap<>(
);
int n =
platform.len
gth;
for(int
i=0;i<n;i++) {

if(hm.contai
nsKey(platfo
rm[i])) {

hm.get(platf
orm[i]).add(i
);
}
else {

ArrayList<Int
eger> temp
= new
ArrayList<>()
;

temp.add(i);

hm.put(platf
orm[i],
temp);
}
}
int ans
= 0;
for(int
key :
hm.keySet())
{
//
max number
of trains for
each key
(i.e.
platform)

ArrayList<Int
eger> curr =
hm.get(key);

Collections.s
ort(curr,
(a,b)-
>depart[a]-
depart[b]);
int
prevDepart
= -1;

for(int
i=0;i<curr.siz
e();i++) {

if(arrive[curr
.get(i)]>prev
Depart) {
finalB.set(y, }
rear=null;
board[x][y]);
}
if(count%2! }
=0) { private }
void }
enqueue(int
}
if(count==1)
x) {
mid =board[i] top;
[j] = -1;
if(size==0)
else } { { package HeapPack;
public
front
staticmid = new
=
Node(x);
ArrayList<Ar
mid.next; public class Queue_Array_Simple {
rayList<Integ
rear
er>>
} = front; int front, rear;
knightTour(i } int capacity;
size
nt n,=int 1; m) { int arr[];
DLLNode /*
return;
temp = top;
Return }
matrix
top.next of= // |4| R <-- Enqueue from here
rear.next
size
new n*m = // |3|
new
where
DLLNode(x); // |2|
Node(x);
integer top // |1| F <-- Dequeue from here
= top.next; atrear public Queue_Array_Simple(int _capacity)
=cell(i,
rear.next;
j) {
represent
top.prev = front=0;
size++;
move
temp; rear=0;
number } of capacity = _capacity;
knight
count++;private
to arr = new int[_capacity];
int
reach } that }
dequeue() cell. {
private
Move
int pop() { //Function to push an element x in a queue.
if(size==0)
number void enqueue(int x)
return
start -1;
from
if(top==null) 0. {
return -1; int // Your code here
temp =It may arr[rear++] = x;
front.data;
be possible
if(count%2! }
that
=0) { there is
if(size==1)
no possible //Function to pop an element from queue and
rear
order =
if(count==1) to visit return that element.
null;
each
; //
cellrear int dequeue()
also points {
at front
exactly
else { // Your code here
once. In that if(front==rear) return -1;
front
case,mid = =
return int front_item = arr[front];
front.next;
amid.prev;
matrix of for(int i=front;i<rear;i++){
size n*m// In arr[i] = arr[i+1];
case
having
} sizeall }
was 1 after
the values } rear--;
dequeue equal return front_item;
both
to -1.
count--; rear }
and front
*/ int boolean isEmpty() {
will
temp = become return front==rear;
null //
top.data; Write }
your code top public static void main(String[] args) {
size--;
here.
= top.prev; Queue_Array_Simple q = new
int[][] Queue_Array_Simple(100);
return
return =temp;
board new
temp; q.enqueue(1);
}}
int[n][m]; q.enqueue(2);
private
for(int[]
private q.enqueue(3);
int
b : size()
board)
int findMid() { q.enqueue(4);
Arrays.fill(b,-
{ while(!q.isEmpty()) {
return
1); size; System.out.println(q.dequeue());
}
if(mid==null) }
return private
ArrayList<Ar -1;
boolean
rayList<Integ }
}
public T
pop() {

return
stackArr[--
top];
}
public
void push(T
item) {

stackArr[top
++] = item;
}
public
public
boolean
void
isFull() {
reverseUsin
gRecursion()
return
{
top==maxSiz//
e-1;
Complexity:
O(n^2)}
public
void
if(this.isEmp
insertAtEnd
ty()) return;
Recursive(TT
x)
temp{ =
this.pop();
if(isEmpty())
{reverseUsin
gRecursion()
this.push(x);
;
return;
insertAtEnd
}
Recursive(te
mp); T
temp} =
this.pop();
public
insertAtEnd
void
Recursive(x);
reverseUsin
gQueue() {
this.push(te
mp);
Queue<T> q
= new }
public
LinkedList<T
void
>();
insertAtEndI
terative(T
while(! x)
{this.isEmpty
())
Stack<T>
{ q.add(this.
auxSt
pop());=}new
Stack<>(max
Size);
while(!
q.isEmpty())
while(!
{ this.push(q
this.isEmpty
.remove()); }
()) }
auxSt.push(t
his.pop());

this.push(x);

while(!
if(size==cap
acity) {
QueueArr[+
+rear] = x;
System.out.}
println("Sorr
ySystem.out.
heap is
full");
println(""fro
nt:
return;
""+front+""
rear: }
""+rear);
heapArr[size
}
] = item;
private
int
upHeapify(si
dequeue() {
ze);
if(front==-1)
size++;
{
System.out.
// empty
println("Afte
rreturn
insertion:
-1;
"+Arrays.toS
tring(heapAr
}else {
r));
}
int temp =
private
QueueArr[fr
void
ont];
downHeapif
y(int idx){
if(front==rea
r) { // only//
compare
one element
with
left
children and
swapfront=-
1; int
child1 =
2*idxrear=-1;
+ 1;
int
child2
}else =
2*idx + 2;
if(front==ca
pacity-1)int { i
= idx;
front =
while(child1
0;
<size &&
child2<size)
}else
{
front++;
if(Math.max
(heapArr[chi
return temp;
ld1],heapArr}
[child2])<he
}
apArr[i])
private
break;
boolean
isEmpty()
Algo explain: { Prioority
Watch from
Queue
16:00
- Down Heapify, Up Heapify and Heap properties: HOP & CBT
if(heapArr[c
hild1]>=hea
return front
pArr[child2])
== -1 &&
{rear == -1;
}
public
swap(i,child
static void
1);
main(String[
] args) {
https://algo.monster/problems/sliding_window_maximum

class
Solution
{
boolean
checkHeap =
true;
int
isHeapUtil(N
ode tree){
//
returns
height

if(tree==null
) return 0;

if(tree.left==
null &&
tree.right!
=null) {

checkHeap =
false;

return -1;
}
int hLeft
=
isHeapUtil(tr
ee.left);
int
hRight =
isHeapUtil(tr
ee.right);
if(hLeft-
hRight>=0){

checkHeap =
checkHeap
&&
(tree.left!
=null?
tree.left.dat
a<tree.data:
true)

&&
(tree.right!
RWw&index=6
new
d[0] = 0;
LinkedList<I
int[]
nteger>();
parent =
for(int
new int[n];
i=0;i<V;i++)
boolean
{ // initialize
updated
queue =
false;
for(int
if(inDegree[i
i=0;i<n-1;i+
]==0)
+){
q.add(i);
}
updated =
false;
q.add(Intege
r.MAX_VAL
for(int
UE);
j=0;j<edges.l
ength;j++){
int
count =0;
if(d[edges[j]
int
[0]]
timer + = 1;
edges[j][2]
int[] <
d[edges[j]
jobTime =
[1]]){
new int[V];
while(!
d[edges[j]
q.isEmpty()){
[1]] = int
d[edges[j]
curr =
[0]] +
q.remove();
edges[j][2];
/
if(curr
/System.out.
==
println(Array
Integer.MAX
s.toString(d)
_VALUE
);
&& !
q.isEmpty()){
parent[edge
s[j][1]]
timer++; =
edges[j][0];
q.add(Intege
updated
r.MAX_VAL =
true;
UE);
}
continue; }
}else
if(updated
if(q.isEmpty(
== false)
)) break;
return 0;
}
int start
ans[count]=
=curr;
Integer.MAX
_VALUE;
jobTime[cur
for(int
r] = timer;
j=0;j<edges.l
ength;j++){
count++; //
in case at
if(d[edges[j]
the end
[0]]
count+ is not
edges[j][2]
equal to V, <
d[edges[j]
means the
[1]]){
given graph
wasn't a
d[edges[j]
DAG
[1]] =
d[edges[j]
ArrayList<Int
[0]] +
true;
PriorityQueu
e<pair1> pq
ArrayList<pa
= new
ir> arr =
PriorityQueu
adj.get(i);
e<>( (a,b) ->
{ return
for(pair
a.weight- child
:b.weight;
arr) { } );
topoSort(chi
pq.add(new
ld.val,adj,visi
pair1(start,0
ted,st);
));
while(!}
pq.isEmpty()
st.push(i);
){
} pair1
curr =private
static
pq.remove() int[]
longestPath
; private
DAG(int
static void s,
int V,
if(visited[cur
DFSpathMor
ArrayList<Ar
r.edge])
eThanK(int
rayList<pair>
continue;
s, int
>k,ArrayList<
adj) {
if(curr.edge=
ArrayList<pa //
expects
=end)
ir>> adj, adj
return
list with
curr.weight;
boolean[]
child and
visited,int
weight
size) { as
visited[curr.
input
edge] = true;
if(visited[s])
Stack<Intege
ArrayList<pa
return;
r>
ir1> stchildren
= new
Stack<Intege
=if(size>=k) {
r>();
adj.get(curr.
edge);
System.out.
boolean[]
println("YES
visited
for(pair1
"); =
new
child :
boolean[V];
children){
return;
}
for(int
pq.add(new
i=0;i<V;i++)
visited[s] = {
pair1(child.e
dge,curr.wei
true;
if(!visited[i])
ght+child.we
topoSort(i,a
ight));
ArrayList<pa
dj,visited,st);
}
ir> children
}
= adj.get(s); }
return -
for(pair
int[]
childdist
1; : =
new } int[V];
children) {
private
Arrays.fill(di
static void
if(visited[chil
st,
fillAdj(Array
d.val])
Integer.MIN
List<ArrayLis
continue;
_VALUE);
t<Integer>>
edgeList,
DFSpathMor
dist[s] = 0;
ArrayList<Ar
eThanK(chil
rayList<pair1
d.val,k,adj,vi
while(!
>> adj){
sited,size+ch
st.isEmpty())
for(int
ild.weight);
{i=0;i<edgeLi
}
st.size();i++){
int curr = =
visited[s]
st.pop();
ArrayList<Int
false;
int V =
tr.insert(wor
adjMat.lengt
ds[i]); //
h;
imported
fromint ans =
TrieDs
0; }
for(int
i=0;i<V;i++) {
TrieNode
startingNod
efor(int
=
j=0;j<V;j++) {
tr.searchQu
ery(query);
for(int
k=0;k<V;k+
ArrayList<Str
+) { arr =
ing>
new
if(i==j ||
ArrayList<Str
i==k || j==k)
ing>();
continue;
tr.DfsSugges
// all
tions(startin
permutation
gNode,"",
s
arr); //
imported
from TrieDS
if(adjMat[i]
[j]==1 &&
for(String
adjMat[j]
str:arr)
{[k]==1 &&
System.out
adjMat[k] Counting sort : Explained
.println(str);
}[i]==1)
// arr ans+
will
+;
contains all
suggestion
} strings
sub
}
}
ArrayList<Str
ing>return
ans =
ans;
new
}
ArrayList<Str Complete code in Auto_Cokplete and TrieDS in BSTpack
ing>();

for(int
i=0;i<k;i++) {
// answer
will create
the final k
results

ans.add(que
ry.substring(
0,query.leng
th()-
1)+arr.get(i))
;
}

System.out.
println(ans);
}
Number
public of Unique BSTs
static void
DfsSuggestio
ns(TrieNode
startingNod
e, String
path,ArrayLi
Burst ballons

O(nlogn) solution Patience sort


static
class node
{
int
data, liss;
node
left, right;

public
node(int
data)
{

this.data =
data;

this.liss = 0;
}
}

private
static int
lissRecursive
(node root) {

if(root==null
) return 0;

if(root.left==
null &&
root.right==
null) {

root.liss = 1;

return 1;
}

if(root.liss!
=0) return
root.liss;
int
ans = 0;
ans
= Math.max(
(lissRecursiv These three questions are conceptually same.
e(root.left) + But have minor differences!
lissRecursive
(root.right)),

(1+
observed

if(hm.contai
nsKey(sum))
longestLen = These three questions are conceptually same.
Math.max(i- But have minor differences!
hm.get(sum)
,longestLen);

if(sum==0)
longestLen =
Math.max(i+
1,longestLen
);

hm.put(sum,
hm.getOrDe
fault(sum,i));
}
return
longestLen;
}

int
largestAreaS
ubMatrixSu
m0(int R, int
C, int M[][])
{
//
create
Number col-
of possible BSTs using n numbers
aux array
(i.e. prefix
sum along
each
column) in
the problem
-
//
Subarray
sum queries
we add both
prev row
and col in
seperate
loops, here
we only do
prev row

int[][]
aux = new
int[R][C]; Use algorithm
like Kadane's, etc. Conceptually same
for(int
i=0;i<R;i++){

for(int
j=0;j<C;j++){

if(i==0)
aux[i][j] =
M[i][j];

//
private
static int
square(int n)
{
int
reqFact = n;
int ans
= 0;

while(reqFac
t>0) {
int
count = 0;
int
num =
Math.abs(n);
int
prev = 0;

while((1<<c
ount)<=reqF
act) {

prev = num;

num <<= 1;

count++;
}

count--;
ans
Remove duplicates from sorted array (Move uniques to one side)

Read Sheet 2 for variations (One missing number) or (one number preset twice) and rest numbers ap

Squares of a Sorted Array (8) - Uses extra space merge operation


Flagship pairsum problem-
Pair Difference (8)
Sorting, followed by two pointer:

Concept - Prefix Sum Count Of Subarrays Having Sum Equals To K with negative numbers (use p

Uses fixed size Sliding window - min sum subarray of size k


Uses variable length sliding windowClick toRelated
see template
problems

Fixed size sliding window problem


Uses KMP algorithm

String Compression (6) - Uses 2 pointer approach

Uses GAP technique (DP)


Longest Palindromic Subsequence (9)
Can be done with Expand around center

Uses LCS
Recursive pattern is similar to LCS One Edit Distance (7) : One loop approach

Word Break II (possible sentences/breaks) (9)

Concept of longest prefix suffix (lps) /


Longest Happy Prefix (10) - Directly uses lps
pie table is created here.

Letter Combinations of a Phone Number (7)

uses Fault algo both left-right traversals


Longest valid bracket substring (9)
same as longest valid bracket substring

Search a Word in a 2D Grid of characters (8 directions) (7)


Uses concept of Fault algo only one side
Question on leetcode
traversal

Uses variable length Sliding window smallest window that contains all characters of string itself (10)
Recursive pattern similar to LCS Regular Expression Matching (8)

Minimum operations to transform one string to another by moving chars

Count of an Element in a Sorted Array (10)

Find Smallest Letter Greater Than Target (8)

https://www.geeksforgeeks.org/search-an-element-in-an-array-where-di
Search in a nearly sorted array

Capacity To Ship Packages Within D Days (10)


ace (unlike arrays). We can simple rearrange the bottom pointers.
Path Sum I (6)

https://leetcode.com/problems/closest-leaf-in-a-binary-tree/
Problem is of Valid Parenthesis family

Decision problem
Optimization problem

Combinations (7)

Longest Balanced parentheses (7)


https://leetcode.com/problems/max-stack/

Monotonic Stack: Usually used when


multiple queries are asked and answer
Next Greater Element II (Circular) (9)
computed is close (Next) to the current
(either to left/right). Stack is LIFO

Different Ways to Add Parentheses (6): Similar to boolean parenth.

Monotonic Stack ( or NGE): Typical


problems where we need to maximize Maximum Score of a Good Subarray (10)
( min number in subarray * <something> )
Cherry Pickup - uses DFS + DP (7)

perties: HOP & CBT


Monotonic Queue/Deque: Unlike
Monotonic Stack,this is commonly used
with sliding window. Queue is FIFO, so it
is easy to update when sliding the
Constrained Subsequence Sum (9)
window. Usually first occurance is
computed when using Queue. Whereas,
Dequeue is used when removal from
both ends is required
Course Schedule II (10)
Minimum Time Visiting All Points (2) : Needs to be done with Greedy app

Cherry Pickup - uses DFS + DP (7)

Verifying Alien Dictonary (simple Hashmap problem) (5)


Flagship Unbounded KS Coin Change (minimum numbers of coins to make change) (any coin syste

Flagship 01KS Subset sum (9)


Flagship 01KS problem. Count number of subsets with sum k(01KS Equivalent of Coin Change I) (9

Delete Operation for Two Strings (9)

Count of LIS (9)


Russian Doll Envelope (9)
Course Scheduling III (Greedy solution - Use max Heap) (5)

Number of poddiblr BSTs (Leetcode)

Uses Concept of MCS Palindrome Partition I

Uses Concept of MCS Different Ways to Add Parentheses (9)


Power of Two (10)

Hamming Distance (10)


ove uniques to one side)

Multiple numbers can repeat any number of times. Array


one number
with numbers
occurs twice
in a limited
and anothernumber
range of 1 to n.isFind
missing
all repeatin
Count triplets with sum smaller than X (9) - Uses PairFour
sumelements
less thanthat
k sum to a given value (10)

Subarray sum equals to Multiple of K (9) Subarray with equal count of 0s and 1s (9)
Frequency of the Most Frequent Element after K increments (8)
Count all Palindromic Substrings (8) Palindrome pairs (2) - Not related uses Trie
Delete Operation for Two Strings (6) - This problem is
Problems
more similar
related
to to
LCSmoving chars to front/back or both (5)

Concatenated Words (10)

Shortest Palindrome (EPALIN) (9)

Minimum number of swaps for bracket balancing (7)

(8 directions) (7)
Substring with Concatenation of All Words (6) - Uses Fixed length sliding window
n-element-in-an-array-where-difference-between-adjacent-elements-is-1/
Chocolate Distribution problem (5) Painters Partition Problem (10)
Path sum II (7)

eaf-in-a-binary-tree/
Subsets II (8) Combination Sum III (7)

Generate Balanced Parentheses (6) : Uses RecursionRemove(min) Invalid Parenthesis (7)


Largest rectangle of 1s in a binary matrix
Largest rectangular Area in Histogram (8)
(uses largest area Histogram) (7)

Largest rectangle of 1s in a binary matrix


Maximum Subarray min product (9)
(uses largest area Histogram) (9)
First negative integer in every window of size “k” (8)Sum of minimum and maximum elements of all subarrays of size
Course Schedule (9)
ap problem) (5)
Coin Change II with only 'd' coins allowed (Not unbounded
Combination
KS) - need
Sumto
IV:use
Looks
classic
likedp
coin
(i.e.
change
try all but
andwith
subtract
a twist
from
(6)
Minimum sum partition (9) Count of ways to partition array such differece equals k (9)

LCS of three strings (8) Longest Repeating Subsequence (9)

Minimum Removals to Make Mountain Array (9) Russian Doll Envelope (9)
Use max Heap) (5)

Palindrome Partition III Palindrome Partition IV


Bulb Switcher III (sum natural numbers) (7)
Triplet sum (10)
Longest Subarray of 1's After Deleting One Element (8)
t/back or both (5)
Sliding window with sub strings and repeating chars:-
Aggressive Cows (8)
Check If Word Is Valid After Substitutions (10)
Prices with special discount - (Next Smaller Element) (9)

Container with most water (7): Uses concept from Trapping rain water and largest area histogram
Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit (8) : VL Sliding window + Deque
nge but with a twist (6)
Shortest Common Supersequence (9)

Maximum Length Chain of Pairs (9)


Boolean Parenthesization Problem
Longest K unique characters substring (7)See similar question related to count of such subarrays/substrings on right
Longest Substring Without Repeating Characters (8)
EKO SPOJ (8)
Reversal of brackets required to balance string (7)
Online Stock Span (9) (NGL)

Remove k digits smallest number (7): Uses stack but not an NGE variant
Greedy Algorithm to find Minimum number of Coins (Canonical System)
Wildcard Matching (7)

Maximum Sum Increasing Subsequence (MSIS) (9)


Drop and sweep problems :-
Corporate Flight Bookings
(uses prefix sum)
Count of subarray/substring problems using
Fruit Into Baskets (7) : Same as Longest subarray/substring with k (2 in this question) unique numbers
variable length sliding window:-
Longest K unique characters substring (8)
Minmum number of swaps to balance brackets (7)
Daily Temperatures(10) Remove Duplicate Letters (7) [Difficult] Revise multiple times

k but not an NGE variant


Coins (Canonical System)
Edit Distance (6) Uncrossed Lines (10)

Longest subsequence such that differencebetween adjacent


Constrained
is one
Subsequence
(9) Sum (9) [IMP] [HARD]:Uses MSIS DP a
Maximum Sum Obtained of Any Permutation Car Pooling
Count of Subarray with product less than k (8) Count of Subarrays with k distinct integers (7)
Minimum ASCII Delete Sum for Two Strings (9) Minimum operations to transform one string to another by mov

Longest Alternating Subsequence /Wiggle Subsequence (9)


Count Of Subarrays Having Sum Equals To K with negative
Longestnumbers
Continuous
(use Subarray
prefix-sum)
With
- Same
Absolute
as line
Diff26Less
(5) Than or Eq
Longest increasing subsequence (LIS) - Can be a solution
Interleaving
for LIS string
Count of Problem: Topic:
Months Array BackTracking Binary Search Trees Binary Trees
Apr 35
May
Jun 19 40
Jul 8
Nov
Total Result 35 8 19 40
Bit Manipulation DoubleLinkedList Dynamic Programming Graph Greedy Heap LinkedList
1
4 56 26
3 42 1
13 1 23 18

13 7 58 42 24 18 26
Matrix Searching & Sorting Stacks & Queues String Trie Math Total Result
9 1 21 67
1 19 106
4 109
30 35 1 6 135
1 1
10 34 36 41 6 1 418
Variations of :
Array find duplicate in an array of N+1 Integers [V V.IMP]

Array Best time to buy and Sell stock


1. Numbers in limited range (such as from 1 to n-1):

(a) one number can repeat multiple times.

(b) one number repeats (one number


comes twice rest come once)

(c) any number can come any number of times.


Number range [0,n-1]

(d) one number occurs twice and another


number is missing

2. Number are not from any range:


(a) One number is unique rest come twice
(b) Two numbers are unique, rest come twice

Best Time to Buy and Sell Stock IIBest Time to Buy and Sell Stock IIIBest Time to Buy and Sell Stock IVBest Time to Buy and Sell Stock with Cooldown
Solution:
rom 1 to n-1):

This can be done using -ve indexing in array (using array itself as a Hashmap) or % approach.
An even better approach is using the floyd cycle detection method on the array (in case we are not allowed to make

Very simple solution: sum - sum using n*(n-1)/2 formula

This problem can only be done by using the original array as Hashmap (two approaches: -ve and %). In case we use t
problems: (a) case when array contains 0. (b) We need to only print repeted items once. The problem (a) can be solv
cannot solve (b). For that we need to swich to the % approach -->
Edge cases are number coming more than once need to be printed only once. See the gfg ediorial for this!

Done using -ve array indexing approach or % approach.

Simple use XOR


Use XOR with a trick (make two groups using RSB of xorAll)

Stock IIIBest Time to Buy and Sell Stock IVBest Time to Buy and Sell Stock with Cooldown
Links

https://leetcode.com/problems/find-the-duplicate-number/submissions/
https://www.youtube.com/watch?v=dfIqLxAf-8s

https://www.geeksforgeeks.org/duplicates-array-using-o1-extra-space-set-2/?ref=rp
The -ve approach works
with range 1 to n-1
and % approach works
with range 0 to n-1

https://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-array-of-repeating-elements/
Couldn't do problems (speed breaker) Reason
636. Exclusive Time of Functions Weird test cases, could not understand question well
224. Basic Calculator and variants
827. Making A Large Island hard
317. Shortest Distance from All Buildings hard
759. Employee Free Time hard
10. Regular Expression Matching feeling irrated, need to try again

You might also like