โš”๏ธ
DSA Important Questions
  • ๐Ÿ˜‡README
  • ๐Ÿ”ซQuestion List
  • ๐ŸงชFormula List
  • ๐Ÿ—’๏ธ01 Array
    • โœ…Rotate Matrix
    • โœ…Max Sum Contiguous Subarray
    • Find Duplicate in Array
    • โœ…Merge Intervals
    • โœ…Spiral Order Matrix I
    • Repeat and Missing Number Array
    • โœ…Merge Overlapping Intervals
    • โœ…Set Matrix Zeros
    • โœ…Spiral Order Matrix II
    • Largest Number
    • First Missing Integer
    • โœ…Pascal Triangle
    • โญMax Distance
    • โœ…Wavy Array
    • Next Permutation
    • โœ…Min Steps in Infinite Grid
    • Flip
    • โญFind Permutation
    • โญMaximum Absolute Difference
    • โญMaximum Unsorted Subarray
    • Reorder Data in Log File
    • โœ…Make equal elements Array
  • โž•02 Math
    • โœ…Excel Column Number
    • โญExcel Column Title
    • โญGrid Unique Paths
    • โญPower Of Two Integers
    • โœ…Next Similar Number
    • โญk-th Permutation
  • ๐Ÿ”03 Binary Search
    • โญMedian of Array
    • โญSquare Root of Integer
    • โญRotated Sorted Array Search
    • โญMatrix Median
    • Capacity To Ship Packages Within B Days
  • ๐Ÿงต04 String
    • Implement StrStr
    • โญInteger to Roman
    • โญRoman to Integer
    • Length of Last Word
    • โญatoi
    • โญValid IP Addresses
    • โญCompare Version Numbers
    • โญLongest Palindromic Substring
    • Count And Say
    • Reverse the String
    • Power of 2
    • ๐ŸšงKMP: Minimum Characters Required to Make a String Palindromic
    • โญConvert to Palindrome
    • Bulls and Cows
  • 1๏ธโƒฃ05 Bit Manipulation
    • Reverse Bits
    • Single Number
    • โญDivide Integers
    • โญSingle Number II
    • โญCount Total Set Bits
    • โญPalindromic Binary Representation
  • โœŒ๏ธ06 Two Pointers
    • Merge Two Sorted Lists II
    • โญ3 Sum
    • Remove Duplicates from sorted Array
    • โญContainer With Most Water
    • Remove Element from Array
    • โญMax Continuous Series of 1s
    • Pair With Given Difference
    • โญMaximum Ones After Modification
  • ๐Ÿ”—07 Linked List
    • Swap List Nodes in Pairs
    • Rotate List
    • โญReorder List
    • Merge Two Sorted Lists
    • Remove Duplicates from Sorted List
    • Add Two Numbers as Lists
    • Remove Nth Node from List End
    • โญList Cycle
    • Intersection of Linked Lists
    • โญReverse Linked List II
    • Palindrome List
    • โญK reverse linked list
    • โญReverse Alternate K Nodes
    • โญKth Node From Middle
    • โญSort Binary Linked List
    • โญEven Reverse
  • ๐Ÿ“š08 Stacks and Queues
    • โญRain Water Trapping
    • Generate all Parentheses
    • โญLargest Rectangle in Histogram
    • โญMin Stack
    • Redundant Braces
    • Nearest Smaller Element
    • โญFirst non-repeating character in a stream of characters
    • โœ…Balanced Parantheses!
  • ๐Ÿ”™09 Backtracking
    • โญKth Permutation Sequence
    • โญCombination Sum
    • Combination Sum II
    • โญNQueens
    • Combinations
    • โญSubsets II
    • Subset
    • Palindrome Partitioning
  • ๐Ÿ’ฑ10 Hashing
    • โญLongest Consecutive Sequence
    • โญ4 Sum
    • โญAnagrams
    • โญPoints on the Straight Line
    • 2 Sum
    • โญValid Sudoku
    • Copy List
    • Longest Substring Without Repeat
  • ๐Ÿ—ป11 Heaps & Maps
    • Merge K Sorted Lists
    • โญLRU Cache
    • โญInversions
    • Distinct Numbers in Window
  • ๐ŸŒณ12 Tree Data Structure
    • โœ…Inorder Traversal
    • โญRecover Binary Search Tree
    • โญInorder Traversal of Cartesian Tree
    • โญLeast Common Ancestor
    • โญConstruct Binary Tree From Inorder And Preorder
    • Flatten Binary Tree to Linked List
    • Valid Binary Search Tree
    • โœ…Preorder Traversal
    • โญBinary Tree From Inorder And Postorder
    • Balanced Binary Tree
    • โœ…Sorted Array To Balanced BST
    • Symmetric Binary Tree
    • โœ…Postorder Traversal
    • โญPopulate Next Right Pointers Tree
    • Identical Binary Trees
    • BST Iterator
    • ZigZag Level Order Traversal BT
    • Path Sum
    • Next Pointer Binary Tree
    • Min Depth of Binary Tree
    • Root to Leaf Paths With Sum
    • โญKth Smallest Element in Tree
    • โญ2-Sum Binary Tree
    • Vertical Order traversal of Binary Tree
    • โญDiagonal Traversal
    • Cousins in Binary Tree
    • Path to Given Node
    • Remove Half Nodes
    • Merge two Binary Tree
    • โญBurn a Tree
    • Nodes at Distance K
    • Vertical Sum of a Binary Tree
    • Covered / Uncovered Nodes
  • 13 Dynamic Programming
    • Ugly Number II
    • Coin Change
    • 0 - 1 Knapsack Problem
    • Permutation Coefficient
  • 14 Greedy Algorithm
    • โญGas Station
    • โญMajority Element
    • โญDistribute Candy
    • โญHighest Product
    • Assign Mice to Holes
    • โญMeeting rooms
  • ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ15 Graph
    • Clone Graph
    • Word Search Board
    • โญStepping Numbers
    • Black Shapes
    • Knight On Chess Board
    • โŒSmallest Multiple With 0 and 1
    • โญCommutable Islands
    • Possibility of finishing all courses given pre-requisites
    • โŒValid Path
    • Cycle in Directed Graph
    • โŒCycle in Undirected Graph
Powered by GitBook
On this page
  • Basic
  • Prevent iterator from moving forward in for loop.
  • Array
  • Binary Search
  • Getting Mid while Avoids Integer Overflow
  • Math
  • GCD Euclid's Formula
  • Fast Exponentiation
  • Compare Numbers Represented as String
  • Removing Leading 0s from a Number in String
  • Compare double type numbers
  • Check whether a double type contains Integer
  • Property of nCr
  • Property of nPr
  • Power of two
  • Bit Manipulation
  • Check if bit is set
  • Set a bit
  • Multiply by 2^k
  • Check if a number is odd or even
  • String
  • Linked List
  • Edge Cases
  • Get Length of a Linked List
  • Get nth Node from Front
  • Get the Last Node of a Linked List
  • Reverse a Linked List
  • Get the Middle Element of a Linked List
  • Binary Tree
  • Iterative Traversal Algorithm

Formula List

PreviousQuestion ListNextRotate Matrix

Last updated 2 years ago

Basic

Prevent iterator from moving forward in for loop.

char ch;

for(int i = 1; i <= 10; i++) {
    cout << "Iteration " << i << endl;
    cout << "repeat iteration (y/n): ";
    cin >> ch;
    
    if(ch == 'y')
    i--;
}

Sometimes you might want to work with the same value of the iterator. Example: See solution for

Array

  • Address of index i = base address + index * size of each element

  • When working with a group of people in a circular arrangement(or any similar situation), think of how a queue might be used here.

Binary Search

Getting Mid while Avoids Integer Overflow

mid=low+((highโˆ’low)>>1)mid=low+((high-low)>>1)mid=low+((highโˆ’low)>>1)

Math

Problem
Approach

Primality Test

Sieve of Eratosthenes

GCD Euclid's Formula

See Main Article

GCD(a,b)={bwhenย a=0awhenย b=0GCD(a%b,b)whenย a>bGCD(a,b%a)whenย b>a\text{GCD}(a, b) = \left\{ \begin{array}{ll} b & \text{when } a = 0 \\ a & \text{when } b = 0 \\ GCD(a \% b, b) & \text{when } a > b \\ GCD(a, b \% a) & \text{when } b > a \\ \end{array} \right.GCD(a,b)=โŽฉโŽจโŽงโ€‹baGCD(a%b,b)GCD(a,b%a)โ€‹whenย a=0whenย b=0whenย a>bwhenย b>aโ€‹

Fast Exponentiation

See Main Article

xn={xn2ร—xn2whenย xย isย evenย andย n>=0xn2ร—xn2ร—xwhenย xย isย oddย andย n>=0xn2ร—xn2whenย xย isย evenย andย n<0xn2ร—xn2ร—1xwhenย xย isย oddย andย n<0x^n=\left\{ \begin{array}{ll} x^\frac{n}{2}\times x^\frac{n}{2}&\text{when x is even and } n >= 0 \\ x^\frac{n}{2}\times x^\frac{n}{2} \times x&\text{when x is odd and } n >= 0 \\ x^\frac{n}{2}\times x^\frac{n}{2}&\text{when x is even and } n < 0 \\ x^\frac{n}{2}\times x^\frac{n}{2} \times \frac{1}{x} &\text{when x is odd and } n < 0 \\ \end{array} \right.xn=โŽฉโŽจโŽงโ€‹x2nโ€‹ร—x2nโ€‹x2nโ€‹ร—x2nโ€‹ร—xx2nโ€‹ร—x2nโ€‹x2nโ€‹ร—x2nโ€‹ร—x1โ€‹โ€‹whenย xย isย evenย andย n>=0whenย xย isย oddย andย n>=0whenย xย isย evenย andย n<0whenย xย isย oddย andย n<0โ€‹

Compare Numbers Represented as String

bool compare(string s1, string s2) { // is s1 smaller than s2
    if(s1.length() == s2.length()) 
        return s1 < s2;
    return s1.length() < s2.length();
}

Useful when comparing extremely large numbers that cannot otherwise be stored in any other data type

Removing Leading 0s from a Number in String

string removeLeadingZeros(string str) {
    int zeros = 0;
    while(zeros < str.size() && str[zeros] == '0')
        zeros++;
        
    return str.substr(zeros);
}

Compare double type numbers

if(abs(a - b) < 1e-9)
	cout << "Same";
else
	cout << "Not Same";

Two double-type numbers could be the same but could evaluate as false due to precision error when compared using == for equality.

Another way to say that two double numbers are equal is to say that the distance between them is less than ฯต\epsilonฯตโ€‹, where ฯต\epsilonฯต is a very small number.โ€‹

Check whether a double type contains Integer

inline bool isInteger(const double &x) {
    return (x - (int)x != 0);
}

If a number is not an integer, for example, 5.5, then its difference with its integer part will be non-zero.

If it is an integer, then the difference is 0.

5.5โˆ’5=0.5โ‰ 05.0โˆ’5=05.5-5=0.5 \ne 0\\ 5.0-5=05.5โˆ’5=0.5๎€ =05.0โˆ’5=0

nCr^nC_rnCrโ€‹

int nCr(int n, int r) {
    if(n == 0 || r == 0 || n == r)
        return 1;

    r = min(r, n - r);

    int res = 1;
    for(int i = 1; i <= r; i++) 
        res = res * (n - i + 1) / i;
    
    return res;
}

Time Complexity: O(min(r,nโˆ’r))O(min(r, n - r))O(min(r,nโˆ’r))

Property of nCr

nCr=nโˆ’1Cr+nโˆ’1Crโˆ’1^nC_r=^{n-1}C_r+^{n-1}C_{r-1}nCrโ€‹=nโˆ’1Crโ€‹+nโˆ’1Crโˆ’1โ€‹
int getnCr(int n, int r, vector<vector<int>> &savedResult) {
    r = min(r, n - r);
    
    if(r == 0)
        return 1;
        
    if(r == 1)
        return n;
        
    if(savedResult[n][r])
        return savedResult[n][r];
        
    return savedResult[n][r] = 
            (getnCr(n - 1, r, savedResult) + getnCr(n - 1, r - 1, savedResult));
}

nPr^nP_rnPrโ€‹

Property of nPr

nPr=nโˆ’1Pr+rร—nโˆ’1Prโˆ’1^nP_r=^{n-1}P_{r}+r \times ^{n-1}P_{r-1}nPrโ€‹=nโˆ’1Prโ€‹+rร—nโˆ’1Prโˆ’1โ€‹
int P(int n, int r) {
    long long nPr[n + 1][r + 1];
    
    for(int i = 1; i <= r; i++)
        nPr[0][i] = 0;
    
    for(int i = 0; i <= n; i++)
        nPr[i][0] = 1;
    
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= r; j++)
            nPr[i][j] = (nPr[i - 1][j] + (j * nPr[i - 1][j - 1])) % 1000000007;
    
    return nPr[n][r];
}

Power of two

(n & (n - 1) == 0) ? "Yes" : "No";

Bit Manipulation

Check if bit is set

bool isSet(int num, int posFromRight) {
    return num & (1 << (posFromRight - 1));
}

Set a bit

int set(int num, int posFromRight) {
    return num | (1 << (posFromRight - 1));
}

Multiply by 2^k

numร—2knum \times 2^knumร—2k

int multiply(int num, int k) {
    return num << k; // num * 2 ^ k
}

Check if a number is odd or even

bool isEven(int num) {
    return (num & 1) ? true : false;
}

String

Problem
Approach

Palindrome Test

Two Pointer Approach

Anagram Test

  • Count of each character in both the strings will be same.

  • Use map or a lookup table.

Linked List

Edge Cases

Case
Problem
Handling

Linked List has single or no elements

Accessing ptr -> next throws an error

if(!A || !(A -> next)) reutrn A

Get Length of a Linked List

int getLength(ListNode* A) {
    int count = 0;
    while(A) {
        count++;
        A = A -> next;
    }
    return count;
}

Get nth Node from Front

Here nโˆˆ[1,A.length]n\in [1, A.length]nโˆˆ[1,A.length]โ€‹

ListNode *getNode(ListNode *A, int n) {
    while(--n) 
        A = A -> next;
    
    return A;
}

Get the Last Node of a Linked List

ListNode* getEnd(ListNode *ll) {
    if(!ll) return ll;
    
    while(ll -> next)
        ll = ll -> next;
        
    return ll;
}

Reverse a Linked List

ListNode *reverseLL(ListNode *ll) {
    ListNode *prev = NULL;
    ListNode *current = ll;
    
    while(current) {
        ListNode *next = current -> next;
        current -> next = prev;
        prev = current;
        current = next;
    }
    
    return prev;
}

Get the Middle Element of a Linked List

ListNode *getMiddle(ListNode *A) {
    ListNode *slow = A, *fast = A;
    while(fast && fast -> next && fast->next->next) {
        slow = slow -> next;
        fast = fast -> next -> next;
    }
    return slow;
}
Odd length: 
    1 2 3 4 5 6 7
          ^
Even Length: 
    1 2 3 4 5 6 7 8
          ^

To get 5 as the middle element in event elements

Initialize fast with head->next

ListNode *getMiddle(ListNode *A) {
    ListNode *slow = A, *fast = next;
    while(fast && fast -> next) {
        slow = slow -> next;
        fast = fast -> next -> next;
    }
    return slow;
}
Odd length: 
    1 2 3 4 5 6 7
          ^
Even Length: 
    1 2 3 4 5 6 7 8
            ^* special, comapre to previous code

Binary Tree

Iterative Traversal Algorithm

Inorder Traversal

vector<int> inOrder(Node* root) {
    vector<int> res;
    stack<Node *> s;
    Node* current = root;
    
    while(current || !s.empty()) {
        while(current) {
            s.push(current);
            current = current->left;
        }
        
        current = s.top();
        s.pop();
        
        res.push_back(current->data);
        current = current->right;
    }
    
    return res;
}

mid = low + (high - low) >> 1 will not work. >>'s precedence is lower, so it needs to be in parentheses.

๐Ÿงช
๐Ÿ’ฃ
First Missing Integer