├── Backtracking ├── Code │ ├── Rat in a Maze.cpp │ ├── Rat in a maze.py │ ├── combinationSum.cpp │ ├── combinationSum.py │ ├── nQueens.cpp │ ├── nQueens.py │ ├── sudokuSolver.cpp │ ├── sudokuSolver.py │ └── wordSearch.cpp ├── Homework │ ├── Rat in a Maze.cpp │ ├── combinationSum.cpp │ ├── nQueens.cpp │ ├── sudokuSolver.cpp │ └── wordSearch.cpp └── Notes │ ├── Backtracking Intro.md │ ├── Combination Sum.md │ ├── N-Queens Problem.md │ ├── Rat in a Maze.md │ └── Sudoku Solver.md ├── C++ ├── Code │ ├── 2dFrame.cpp │ ├── 2dWall.cpp │ ├── 2dWallNumbers.cpp │ ├── Find minimum and maximum element in an array.cpp │ ├── FizzBuzz.cpp │ ├── FizzBuzzElseIf.cpp │ ├── ReverseAnArray.cpp │ ├── SearchElementInArray.cpp │ ├── Switch.cpp │ ├── array.cpp │ ├── assignmentOperators.cpp │ ├── binaryArithmeticOperators.cpp │ ├── diamond.cpp │ ├── dowhileLoop.cpp │ ├── elementAppearsOnce.cpp │ ├── eligibleToVote.cpp │ ├── factorial.cpp │ ├── factorialUsingFunction.cpp │ ├── factorialUsingLoop.cpp │ ├── firstProgram.cpp │ ├── forLoop.cpp │ ├── logicalOperators.cpp │ ├── multipleOf2.cpp │ ├── numberPyramid.cpp │ ├── numericalDiamond.cpp │ ├── prePostIncrement.cpp │ ├── primeOrNot.cpp │ ├── reverseRightTriangle.cpp │ ├── rightTriangle.cpp │ ├── rotateArray.cpp │ ├── ternaryOperator.cpp │ ├── whileLoop.cpp │ └── zeroOnePyramid.cpp ├── Homework │ ├── 2DWallUsingFunction.cpp │ ├── diamond.cpp │ ├── initializeWithSameValue.cpp │ ├── productOfArrayElement.cpp │ ├── rightTriangleUsingFunction.cpp │ └── sumOfArrayElements.cpp └── Notes │ ├── Arrays.md │ ├── C++ Intro.md │ ├── Contol Statements.md │ ├── Functions.md │ ├── Operators.md │ ├── Pattern Printing.md │ ├── XOR.md │ ├── conditionals.md │ ├── datatypes.md │ ├── explaination.md │ └── loops.md ├── README.md ├── Recursion ├── Code │ ├── NthStair.c │ ├── NthStair.cpp │ ├── NthStair.java │ ├── NthStair.py │ ├── Subsequences.cpp │ ├── Subsequences.java │ ├── Subsequences.py │ ├── factorials.c │ ├── factorials.cpp │ ├── factorials.java │ ├── factorials.py │ ├── nthFibonacci.c │ ├── nthFibonacci.cpp │ ├── nthFibonacci.java │ ├── nthFibonacci.py │ ├── palindrome.cpp │ ├── palindrome.py │ ├── powerOf2.c │ ├── powerOf2.cpp │ ├── powerOf2.java │ ├── powerOf2.py │ ├── subsetSum.cpp │ ├── subsetSum.py │ ├── subsets.cpp │ ├── sumFirstN.c │ ├── sumFirstN.cpp │ ├── sumFirstN.java │ └── sumFirstN.py ├── Homework │ ├── Subsequences.cpp │ ├── Subsets.cpp │ ├── factorial.cpp │ ├── fibonacci.cpp │ ├── nthStair.cpp │ ├── palindrome.cpp │ ├── permutations.cpp │ ├── possibleWordsFromPhone.cpp │ ├── reverse.cpp │ └── subsetSum.cpp └── Notes │ ├── Recursion Notes - Day 1.md │ ├── Recursion Notes - Day 2.md │ ├── Recursion Notes - Day 3.md │ ├── Recursion Notes - Day 4.md │ ├── Recursion Notes - Day 5.md │ ├── Recursion Notes - Day 6.md │ ├── Recursion Notes - Day 7.md │ ├── Recursion Notes - Day 8.md │ └── Recursion Notes - Day 9.md └── Sorting ├── Code ├── mergeSort.cpp ├── mergeSort.py ├── quickSort.cpp └── quickSort.py ├── Homework ├── mergeSort.cpp └── quickSort.cpp └── Notes ├── Merge Sort.md └── Quick Sort.md /Backtracking/Code/Rat in a Maze.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | vectorans; 4 | 5 | bool isSafe(vector> &m,vector> &visited,int srcx,int srcy,int n){ 6 | if(srcx>=0 && srcy>=0 && srcx> &m,vector> &visited,intn,int srcx,int srcy,string temp){ 13 | if(srcx == n-1 && srcy == n-1){ 14 | ans.push_back(temp); 15 | return; 16 | } 17 | visited[srcx][srcy]=1; 18 | if(isSafe(m,visited,srcx+1,srcy,n)){ 19 | helper(m,visited,n,srcx+1,srcy,temp+"D"); 20 | } 21 | if(isSafe(m,visited,srcx,srcy-1,n)){ 22 | helper(m,visited,n,srcx,srcy-1,temp+"L"); 23 | } 24 | if(isSafe(m,visited,srcx,srcy+1,n)){ 25 | helper(m,visited,n,srcx,srcy+1,temp+"R"); 26 | } 27 | if(isSafe(m,visited,srcx-1,srcy,n)){ 28 | helper(m,visited,n,srcx-1,srcy,temp+"U"); 29 | } 30 | visited[srcx][srcy]=0; 31 | } 32 | vectorfindPath(vector>&m,intn){ 33 | // Your code goes here 34 | if(m[0][0]==0)return ans; 35 | vector> visited(n,vector(n,0)); 36 | helper(m,visited,n,0,0,""); 37 | return ans; 38 | ] -------------------------------------------------------------------------------- /Backtracking/Code/Rat in a maze.py: -------------------------------------------------------------------------------- 1 | def valid_path(maze, i, j, m, n): 2 | if i == m or j == n: 3 | return False 4 | if maze[i][j] == 1: 5 | return False 6 | return True 7 | 8 | def rat_maze(maze, i, j, m, n, arr): 9 | if arr[-1][-1] == 1: 10 | return True 11 | if valid_path(maze, i, j, m, n): 12 | arr[i][j] = 1 13 | if rat_maze(maze, i + 1, j, m, n, arr): 14 | return True 15 | if rat_maze(maze, i, j + 1, m, n, arr): 16 | return True 17 | arr[i][j] = 0 18 | return False 19 | rows = int(input("Enter number of rows in maze:" )) 20 | columns = int(input("Enter number of columns in maze:" )) 21 | maze = [] 22 | for i in range(0,rows): 23 | print('Please enter elements of row',i+1) 24 | lst = [] 25 | for j in range(0,columns): 26 | Element = int(input("Enter element in maze (0/1):" )) 27 | lst.append(Element) 28 | maze.append(lst) 29 | 30 | arr = [[0 for i in range(len(maze[0]))] for j in range(len(maze))] 31 | rat_maze(maze, 0, 0, len(maze), len(maze[0]), arr) 32 | a = " " 33 | for i in arr: 34 | for j in i: 35 | if j==0: 36 | a = "Nothing" 37 | elif j==1: 38 | a = "Filled" 39 | break 40 | if a == "Nothing": 41 | print("No solution") 42 | else: 43 | for i in arr: 44 | print(i) -------------------------------------------------------------------------------- /Backtracking/Code/combinationSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> ans; 4 | 5 | void helper(vector& candidates, int target,int i,int curSum, vector temp){ 6 | // Bounding Condition 7 | if (curSum>target){ 8 | return; 9 | } 10 | // Base Condition 11 | if (i==candidates.size()){ 12 | if(curSum==target){ 13 | ans.push_back(temp); 14 | } 15 | return; 16 | } 17 | // Inclusion 18 | curSum+=candidates[i]; 19 | temp.push_back(candidates[i]); 20 | helper(candidates,target,i,curSum,temp); 21 | curSum-=candidates[i]; 22 | temp.pop_back(); 23 | 24 | // Exclusion 25 | helper(candidates,target,i+1,curSum,temp); 26 | } 27 | vector> combinationSum(vector& candidates, int target) { 28 | vector temp; 29 | helper(candidates,target,0,0,temp); 30 | return ans; 31 | 32 | } 33 | }; -------------------------------------------------------------------------------- /Backtracking/Code/combinationSum.py: -------------------------------------------------------------------------------- 1 | # Python program to find all combinations under given constraints 2 | 3 | def function(candidates, add): 4 | result = [] 5 | m = [] 6 | 7 | # Sorting the List and removing the duplicates using Set 8 | candidates = sorted(list(set(candidates))) 9 | Num(result, candidates, m, add, 0) 10 | return result 11 | 12 | def Num(result, candidates, m, add, index): 13 | 14 | if(add == 0): 15 | 16 | # Adding copy of list to result 17 | result.append(list(m)) 18 | return 19 | 20 | # Iterating from index to len(candidates) - 1 21 | for i in range(index, len(candidates)): 22 | 23 | # Checking that sign of add 24 | if(add - candidates[i]) >= 0: 25 | 26 | # Adding element which to contribute in add 27 | m.append(candidates[i]) 28 | Num(result, candidates, m, add-candidates[i], i) 29 | 30 | # Removing element from list 31 | m.remove(candidates[i]) 32 | 33 | 34 | # Main Code 35 | candidates = [] 36 | n = int(input("Enter the number of candidates:")) 37 | add = int(input("Enter target:")) 38 | for a in range(0,n): 39 | element = int(input("Enter candidate:")) 40 | candidates.append(element) #adding every candidate in candidates 41 | result = function(candidates, add) 42 | 43 | # If output is empty 44 | if len(result) <= 0: 45 | print("empty") 46 | 47 | # Printing sored results 48 | for i in range(len(result)): 49 | 50 | print("(", end=' ') 51 | for j in range(len(result[i])): 52 | print(str(result[i][j])+" ", end=' ') 53 | print(")", end=' ') 54 | -------------------------------------------------------------------------------- /Backtracking/Code/nQueens.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | vector> ans; 13 | 14 | bool isSafe(vector>& board, int r, int c, int n){ 15 | for(int i=0;i=0 && j>=0; i--,j--){ 22 | if(board[i][j]==1){ 23 | return false; 24 | } 25 | } 26 | 27 | for(int i=r-1,j=c+1;i>=0 && j>& board, int n,int r){ 37 | if (r==n){ 38 | vector temp; 39 | for(int i=0;i> nQueen(int n) { 59 | // code here 60 | vector> board(n,vector(n,0)); 61 | helper(board,n,0); 62 | return ans; 63 | } 64 | }; 65 | 66 | // { Driver Code Starts. 67 | 68 | int main(){ 69 | int t; 70 | cin>>t; 71 | while(t--){ 72 | int n; 73 | cin>>n; 74 | 75 | Solution ob; 76 | vector> ans = ob.nQueen(n); 77 | if(ans.size() == 0) 78 | cout<<-1<<"\n"; 79 | else { 80 | for(int i = 0;i < ans.size();i++){ 81 | cout<<"["; 82 | for(int u: ans[i]) 83 | cout<=0 and j>=0): 47 | if board[i][j] == 1: 48 | return False 49 | i = i-1 50 | j = j-1 51 | 52 | i = row-1 53 | j = col+1 54 | while(i>=0 and j=0): 63 | if board[i][j] == 1: 64 | return False 65 | i = i+1 66 | j = j-1 67 | 68 | i = row+1 69 | j = col+1 70 | while(i 3 | using namespace std; 4 | // UNASSIGNED is used for empty cells in sudoku grid 5 | #define UNASSIGNED 0 6 | 7 | // N is used for the size of Sudoku grid. 8 | // Size will be NxN 9 | #define N 9 10 | 11 | 12 | // } Driver Code Ends 13 | class Solution 14 | { 15 | public: 16 | //Function to find a solved Sudoku. 17 | bool check(int grid[N][N],int row, int col, int num){ 18 | //row 19 | for(int i=0;i<9;i++){ 20 | if(grid[i][col]==num) return false; 21 | } 22 | //col 23 | for(int j=0;j<9;j++){ 24 | if(grid[row][j]==num) return false; 25 | } 26 | //box 27 | int ini =row-row%3; 28 | int inj=col-col%3; 29 | 30 | for(int i=0;i<3;i++){ 31 | for(int j=0;j<3;j++){ 32 | if(grid[ini+i][inj+j]==num) return false; 33 | } 34 | } 35 | 36 | return true; 37 | } 38 | bool helper(int grid[N][N], int row ,int col){ 39 | if (row==9) return true; 40 | if (col==9) return helper(grid,row+1,0); 41 | if (grid[row][col] != 0) return helper(grid,row,col+1); 42 | 43 | for(int i=1;i<=9;i++){ 44 | if (check(grid,row,col,i)){ 45 | grid[row][col]=i; 46 | if (helper(grid,row,col+1)){ 47 | return true; 48 | } 49 | } 50 | grid[row][col]=0; 51 | } 52 | return false; 53 | 54 | } 55 | bool SolveSudoku(int grid[N][N]) 56 | { 57 | // Your code here 58 | return helper(grid,0,0); 59 | } 60 | 61 | //Function to print grids of the Sudoku. 62 | void printGrid (int grid[N][N]) 63 | { 64 | // Your code here 65 | 66 | for(int i=0;i<9;i++){ 67 | for(int j=0;j<9;j++){ 68 | cout<>t; 79 | while(t--) 80 | { 81 | int grid[N][N]; 82 | 83 | for(int i=0;i<9;i++) 84 | for(int j=0;j<9;j++) 85 | cin>>grid[i][j]; 86 | 87 | Solution ob; 88 | 89 | if (ob.SolveSudoku(grid) == true) 90 | ob.printGrid(grid); 91 | else 92 | cout << "No solution exists"; 93 | 94 | cout<>& board,string word,int i,int j,int n,int m,int k){ 4 | if(k >= word.size())return true; 5 | if(i<0 || i>=n || j<0 || j>=m || board[i][j]=='.' || word[k]!=board[i][j]) return false; 6 | if(word.size() == 1 && word[k]==board[i][j]) return true; 7 | board[i][j] = '.'; 8 | bool temp = false; 9 | int x[4] = {0,0,-1,1}; 10 | int y[4] = {-1,1,0,0}; 11 | for(int index=0;index<4;index++){ 12 | temp = temp || helper(board,word,i+x[index],j+y[index],n,m,k+1); 13 | } 14 | board[i][j] = word[k]; 15 | return temp; 16 | } 17 | 18 | bool exist(vector>& board,string word) { 19 | int n=board.size(); 20 | if(n==0) return false; 21 | int m=board[0].size(); 22 | if(word.size()==0) return false; 23 | for(int i=0;ians; 4 | 5 | bool isSafe(vector> &m,vector> &visited,int srcx,int srcy,int n){ 6 | if(srcx>=0 && srcy>=0 && srcx> &m,vector> &visited,intn,int srcx,int srcy,string temp){ 13 | if(srcx == n-1 && srcy == n-1){ 14 | ans.push_back(temp); 15 | return; 16 | } 17 | visited[srcx][srcy]=1; 18 | if(isSafe(m,visited,srcx+1,srcy,n)){ 19 | helper(m,visited,n,srcx+1,srcy,temp+"D"); 20 | } 21 | if(isSafe(m,visited,srcx,srcy-1,n)){ 22 | helper(m,visited,n,srcx,srcy-1,temp+"L"); 23 | } 24 | if(isSafe(m,visited,srcx,srcy+1,n)){ 25 | helper(m,visited,n,srcx,srcy+1,temp+"R"); 26 | } 27 | if(isSafe(m,visited,srcx-1,srcy,n)){ 28 | helper(m,visited,n,srcx-1,srcy,temp+"U"); 29 | } 30 | visited[srcx][srcy]=0; 31 | } 32 | vectorfindPath(vector>&m,intn){ 33 | // Your code goes here 34 | if(m[0][0]==0)return ans; 35 | vector> visited(n,vector(n,0)); 36 | helper(m,visited,n,0,0,""); 37 | return ans; 38 | ] -------------------------------------------------------------------------------- /Backtracking/Homework/combinationSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> ans; 4 | 5 | void helper(vector& candidates, int target,int i,int curSum, vector temp){ 6 | // Bounding Condition 7 | if (curSum>target){ 8 | return; 9 | } 10 | // Base Condition 11 | if (i==candidates.size()){ 12 | if(curSum==target){ 13 | ans.push_back(temp); 14 | } 15 | return; 16 | } 17 | // Inclusion 18 | curSum+=candidates[i]; 19 | temp.push_back(candidates[i]); 20 | helper(candidates,target,i,curSum,temp); 21 | curSum-=candidates[i]; 22 | temp.pop_back(); 23 | 24 | // Exclusion 25 | helper(candidates,target,i+1,curSum,temp); 26 | } 27 | vector> combinationSum(vector& candidates, int target) { 28 | vector temp; 29 | helper(candidates,target,0,0,temp); 30 | return ans; 31 | 32 | } 33 | }; -------------------------------------------------------------------------------- /Backtracking/Homework/nQueens.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | vector> ans; 13 | 14 | bool isSafe(vector>& board, int r, int c, int n){ 15 | for(int i=0;i=0 && j>=0; i--,j--){ 22 | if(board[i][j]==1){ 23 | return false; 24 | } 25 | } 26 | 27 | for(int i=r-1,j=c+1;i>=0 && j>& board, int n,int r){ 37 | if (r==n){ 38 | vector temp; 39 | for(int i=0;i> nQueen(int n) { 59 | // code here 60 | vector> board(n,vector(n,0)); 61 | helper(board,n,0); 62 | return ans; 63 | } 64 | }; 65 | 66 | // { Driver Code Starts. 67 | 68 | int main(){ 69 | int t; 70 | cin>>t; 71 | while(t--){ 72 | int n; 73 | cin>>n; 74 | 75 | Solution ob; 76 | vector> ans = ob.nQueen(n); 77 | if(ans.size() == 0) 78 | cout<<-1<<"\n"; 79 | else { 80 | for(int i = 0;i < ans.size();i++){ 81 | cout<<"["; 82 | for(int u: ans[i]) 83 | cout< 3 | using namespace std; 4 | // UNASSIGNED is used for empty cells in sudoku grid 5 | #define UNASSIGNED 0 6 | 7 | // N is used for the size of Sudoku grid. 8 | // Size will be NxN 9 | #define N 9 10 | 11 | 12 | // } Driver Code Ends 13 | class Solution 14 | { 15 | public: 16 | //Function to find a solved Sudoku. 17 | bool check(int grid[N][N],int row, int col, int num){ 18 | //row 19 | for(int i=0;i<9;i++){ 20 | if(grid[i][col]==num) return false; 21 | } 22 | //col 23 | for(int j=0;j<9;j++){ 24 | if(grid[row][j]==num) return false; 25 | } 26 | //box 27 | int ini =row-row%3; 28 | int inj=col-col%3; 29 | 30 | for(int i=0;i<3;i++){ 31 | for(int j=0;j<3;j++){ 32 | if(grid[ini+i][inj+j]==num) return false; 33 | } 34 | } 35 | 36 | return true; 37 | } 38 | bool helper(int grid[N][N], int row ,int col){ 39 | if (row==9) return true; 40 | if (col==9) return helper(grid,row+1,0); 41 | if (grid[row][col] != 0) return helper(grid,row,col+1); 42 | 43 | for(int i=1;i<=9;i++){ 44 | if (check(grid,row,col,i)){ 45 | grid[row][col]=i; 46 | if (helper(grid,row,col+1)){ 47 | return true; 48 | } 49 | } 50 | grid[row][col]=0; 51 | } 52 | return false; 53 | 54 | } 55 | bool SolveSudoku(int grid[N][N]) 56 | { 57 | // Your code here 58 | return helper(grid,0,0); 59 | } 60 | 61 | //Function to print grids of the Sudoku. 62 | void printGrid (int grid[N][N]) 63 | { 64 | // Your code here 65 | 66 | for(int i=0;i<9;i++){ 67 | for(int j=0;j<9;j++){ 68 | cout<>t; 79 | while(t--) 80 | { 81 | int grid[N][N]; 82 | 83 | for(int i=0;i<9;i++) 84 | for(int j=0;j<9;j++) 85 | cin>>grid[i][j]; 86 | 87 | Solution ob; 88 | 89 | if (ob.SolveSudoku(grid) == true) 90 | ob.printGrid(grid); 91 | else 92 | cout << "No solution exists"; 93 | 94 | cout<>& board, string word,int i,int j,int n,int m,int k) { 4 | if(k>=word.size()) return true; 5 | if(i<0 || i>=n || j<0 || j>=m || board[i][j]=='.' || word[k]!=board[i][j]) return false; 6 | if(word.size()==1 && word[k]==board[i][j]) return true; 7 | board[i][j] = '.'; 8 | bool temp= false; 9 | int x[4] = {0,0,-1,1}; 10 | int y[4] = {-1,1,0,0}; 11 | for(int index=0;index<4;index++){ 12 | temp =temp || helper(board,word,i+x[index],j+y[index],n,m,k+1); 13 | } 14 | board[i][j] = word[k]; 15 | return temp; 16 | } 17 | bool exist(vector>& board, string word){ 18 | int n=board.size(); 19 | if(n==0) return false; 20 | int m=board[0].size(); 21 | if(word.size()==0) return false; 22 | for(int i=0;itarget (this is the condition that separates recursion from backtracking and reduces the number of possibilities we need to check) 10 | 11 | **Base Condition :** return back when the array ends 12 | 13 | **Variables required :** 14 | 1. tempAns to store the possible elements (starts empty) 15 | 2. currentSum to store the current sum of tempAns (starts as 0) 16 | 3. index i to keep track of our position (starts as 0) -------------------------------------------------------------------------------- /Backtracking/Notes/N-Queens Problem.md: -------------------------------------------------------------------------------- 1 | ### N-Queens Problem 2 | 3 | **Problem :** Place N Queens in a NxN matrix such that no queen can attack one another 4 | 5 | **Background Knowledge :** 6 | - A Queen in a chess board is a piece that can move in 8 possible directions : front, back, left, right, front-left diagonal, front-right diagonal, back-left diagonal, back-right diagonal. 7 | - A queen in chess can attack the other queen if they are along the same line where their movement is legally allowed according to the rule discussed above 8 | 9 | **Approach :** We have to place one queen in each row and each column since the queens in same row and/or column will always attack one another. So we start by placing the 1st queen in the first column of the first row, then we move to the next row and keep trying to place a queen in feasible locations one by one, When we get a feasible location we try placing the next queen in feasible locations. If we are able to find feasible location, we continue or else we backtrack to the previous row, if we are unable to find a feasible location. Then we again try to rearrange the previous row. We continue like this : moving forward on achieving a feasible location and backtracking to the previous rows if we didn't find a feasible location. This process continues until we get a possible solution. 10 | -------------------------------------------------------------------------------- /Backtracking/Notes/Rat in a Maze.md: -------------------------------------------------------------------------------- 1 | ### Rat in a Maze Problem 2 | 3 | **Question :** There is a rat at one corner of a matrix (2D-Array), and it needs to go to the opposite corner. But it can only go via the spots that have 1 stored in them, the spots that have 0 are like walls where the rat can not move. We need to find all the possible paths that he can take. 4 | 5 | **Note :** 6 | - The mouse can move in 4 directions up, down, right and left but not diagonal 7 | - In questions where we have to find all possibilities we use recursion or backtracking 8 | - If source cell(0,0) is filled with 0, then the rat can not enter the maze hence no possibilities 9 | - Rat can visit one cell only once, o you can not enter a cell twice (To ensure this condition we will make another visited matrix) 10 | 11 | **Requirements :** 12 | - Original matrix 13 | - Visited matrix 14 | - Checking the current position 15 | - Follow Lexicographic order (Dictionary order DLRU "Down-Left-Right-Up") 16 | - variable x & y 17 | 18 | **Approach :** We start from source (0,0) And check if we can move down if so, we go down increase x by 1 and mark 1 in corresponding location in visited matrix and put D in path, and we do this again, in case we get stuck we try other 3 possibilities in lexicographical order and correspondingly change values of x and y and add the movement to path and mark 1 in visited spot and we do this for all spots on by one as we move. Finally we reach the matrix-end and get one possible desired path or else we reach a dead-end. And then we backtrack and again start to try out other paths in lexicographic way from the start and so on. 19 | 20 | This is also known as DFS (Depth First Search in Graphs) 21 | 22 | **Conditions that we are checking :** 23 | 1. x=0 25 | 3. y=0 27 | 5. visited[x][y]=0 28 | 6. m[x][y]=0 29 | 30 | If all these conditions are true then we are safe and we continue -------------------------------------------------------------------------------- /Backtracking/Notes/Sudoku Solver.md: -------------------------------------------------------------------------------- 1 | ### Sudoku Solver 2 | 3 | **Background Knowledge :** 4 | 5 | - Sudoku is made up of three 3x3 matrix which are placed such that they create a bigger 9x9 matrix. 6 | 7 | - Sudoku consists of numbers 1 to 9. 8 | 9 | - There is no same/repeated number in a row 10 | 11 | - There is no same/repeated number in a column 12 | 13 | - There is no same/repeated number in a 3x3 matrix 14 | 15 | **Approach :** 16 | 17 | We will try 1-9 possible values for each position and move forward with each correct value, in case we are able to get an answer we move forward, otherwise we backtrack. And to ensure backtracking we create 3 checks that there is no same number in a row, no same number in a column and no same number in a 3x3 matrix 18 | 19 | One important thing is that to find the starting index of any box we can make use of %3 20 | 21 | This execution will end/return back when row=9 or when we reach the end of the 9x9 matrix -------------------------------------------------------------------------------- /C++/Code/2dFrame.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | int r,c; 7 | cin>>r>>c; 8 | 9 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | int r,c; 7 | cin>>r>>c; 8 | 9 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | int r,c; 7 | cin>>r>>c; 8 | 9 | for(int i=0;i 3 | using namespace std; 4 | #define ll long long 5 | 6 | pair getMinMax(long long a[], int n) ; 7 | 8 | int main() { 9 | int t; 10 | cin >> t; 11 | while (t--) { 12 | int n; 13 | cin >> n; 14 | ll a[n]; 15 | for (int i = 0; i < n; i++) cin >> a[i]; 16 | 17 | pair pp = getMinMax(a, n); 18 | 19 | cout << pp.first << " " << pp.second << endl; 20 | } 21 | return 0; 22 | }// } Driver Code Ends 23 | 24 | 25 | pair getMinMax(long long a[], int n) { 26 | int mn=100000000001; 27 | int mx=0; 28 | for(int i=0;imx){ 31 | mx=a[i]; 32 | } 33 | 34 | //min 35 | if(a[i] ans; //pair is another data type; its elements are accessed via first and second 41 | ans.first = mn; 42 | ans.second = mx; 43 | 44 | return ans; 45 | } -------------------------------------------------------------------------------- /C++/Code/FizzBuzz.cpp: -------------------------------------------------------------------------------- 1 | // FizzBuzz program 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; 8 | cout << "Enter number : "; 9 | cin >> n; 10 | 11 | // % is called mod operator and finds the reminder when n is divided by 3 and the reminder when its divided by 5 12 | if (n%3==0 && n%5==0){ //Checking if n is divisible by both 3 & 5 13 | cout<<"bang "; 14 | } else { 15 | if (n%3 == 0){ 16 | cout << "fizz "; 17 | } else { 18 | if (n%5 == 0){ 19 | cout << "buzz "; 20 | } else { 21 | cout << "sad "; 22 | } 23 | } 24 | } 25 | 26 | //As you can see this code has too many nested if-else which doesn't look good (nested means if-else inside if-else) 27 | } -------------------------------------------------------------------------------- /C++/Code/FizzBuzzElseIf.cpp: -------------------------------------------------------------------------------- 1 | // FizzBuzz program but with if, else-if and else 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; 8 | cout << "Enter number : "; 9 | cin >> n; 10 | 11 | if (n%3==0 && n%5==0){ 12 | cout<<"bang "; 13 | } else if (n%3 == 0){ 14 | cout << "fizz "; 15 | } else if (n%5 == 0){ 16 | cout << "buzz "; 17 | } else { 18 | cout << "sad "; 19 | } 20 | } 21 | 22 | // Using else-if allows for a better code -------------------------------------------------------------------------------- /C++/Code/ReverseAnArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | int arr[100]; 8 | 9 | while(t--){ 10 | int n; 11 | cin>>n; 12 | 13 | for(int i=0;i>arr[i]; 15 | } 16 | 17 | // Reverse 18 | for(int i=0,j=n-1;i 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution{ 8 | public: 9 | // Function to search x in arr 10 | // arr: input array 11 | // X: element to be searched for 12 | int search(int arr[], int N, int X) 13 | { 14 | for(int i=0;i>testcases; 32 | while(testcases--) 33 | { 34 | int sizeOfArray; 35 | cin>>sizeOfArray; 36 | int arr[sizeOfArray]; 37 | int x; 38 | 39 | for(int i=0;i>arr[i]; 42 | } 43 | cin>>x; 44 | Solution ob; 45 | cout< 7 | using namespace std; 8 | 9 | int main(){ 10 | int n; 11 | cout <<"Enter a number : "; 12 | cin >> n; 13 | 14 | switch (n%3) 15 | { 16 | case 0: 17 | cout<<"hello "; 18 | break; // break tells that get out of this switch statement & don't execute any line after this 19 | // if you do not put break here then after getting a correct condition all other statement including those of other cases below it will be executed 20 | 21 | case 1: 22 | cout<<"sad "; 23 | break; 24 | 25 | case 2: 26 | cout<<"close "; 27 | break; 28 | 29 | default: // default executes is no other condition is true 30 | break; 31 | } 32 | } -------------------------------------------------------------------------------- /C++/Code/array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //Passing in a function 5 | void printArray(int arr[], int size){ //Array is passed by reference by default 6 | 7 | arr[2]=179; 8 | 9 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main(){ 5 | int a = 5; 6 | int b = 15; 7 | cout< 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | int a = 20; 7 | int b = 10; 8 | 9 | cout<<"a+b "< 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | int r; 7 | cin>>r; 8 | 9 | int spaces = r-1; 10 | 11 | for(int i=0;i0;i--){ 24 | for(int j=0;j 2 | using namespace std; 3 | 4 | int main(){ 5 | int i = -1; //in while & do while loop you must initialize a variable before hand 6 | 7 | do { 8 | cout<<"hello code in 10 fam"<0); // Note : this condition was not even true but still the program executed once because of do-while loop 11 | } -------------------------------------------------------------------------------- /C++/Code/elementAppearsOnce.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Brute Force solution is the simplest approach that we try when it first comes to our mind. 3 | It is just a first idea, and therefore is mostly not the best way to solve the problem. 4 | 5 | To solve this problem the brute force approach will be to count how many times each element occurs 6 | and store this data in some other array, but this will take more time and space 7 | 8 | So an optimized approach will be to use XOR operation, this operation fives 0 if 2 elements are different 9 | and 1 if both are different 10 | Also, 11 | n^n = 0 12 | n^0 = n 13 | */ 14 | 15 | // { Driver Code Starts 16 | #include 17 | 18 | using namespace std; 19 | 20 | // } Driver Code Ends 21 | //User function template for C++ 22 | class Solution{ 23 | public: 24 | int search(int A[], int N){ 25 | //code 26 | int ans = 0; 27 | for(int i=0;i>t; 41 | while(t--) 42 | { 43 | cin>>len; 44 | int arr[len]; 45 | for(int i=0;i>arr[i]; 47 | } 48 | Solution ob; 49 | cout< 2 | using namespace std; 3 | 4 | int main(){ 5 | int age; // Created a variable of type int to hold age 6 | cin>>age; // Inputted age from the user 7 | 8 | if (age < 18){ // Checking if user is less than 18 9 | cout << "Not Eligible to Vote"; 10 | } else { 11 | cout << "Eligible to Vote"; 12 | } 13 | } -------------------------------------------------------------------------------- /C++/Code/factorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int factorial(int n){ 5 | int ans = 1; 6 | for(int i=1;i<=n;i++){ 7 | ans = ans * i; 8 | } 9 | return ans; 10 | } 11 | 12 | int main(){ 13 | int n; 14 | cin>>n; 15 | 16 | while(n>0){ 17 | n--; 18 | int t; 19 | cin >> t; 20 | cout< 2 | using namespace std; 3 | 4 | int factorial(int n){ 5 | int ans = 1; 6 | for(int i=1;i<=n;i++){ 7 | ans = ans * i; 8 | } 9 | return ans; 10 | } 11 | 12 | int main(){ 13 | int n; 14 | cin>>n; 15 | cout< 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | int n; 7 | cin>>n; 8 | int ans = 1; 9 | for(int i=1;i<=n;i++){ 10 | ans = ans * i; 11 | } 12 | cout<<"factorial of "<>n; 15 | ans = 1; 16 | for(int i=1;i<=n;i++){ 17 | ans = ans * i; 18 | } 19 | cout<<"factorial of "<>n; 22 | ans = 1; 23 | for(int i=1;i<=n;i++){ 24 | ans = ans * i; 25 | } 26 | cout<<"factorial of "< 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | 7 | cout << "Code in 10 FAM"; 8 | 9 | } 10 | -------------------------------------------------------------------------------- /C++/Code/forLoop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | for(int i=0;i<10 && i>5;i=i+1){ // executes when value of i is greater than 5 and less than 10 7 | //So this will not run even once bcz in start value of i is not greater than 5, so loop is never executed 8 | cout <<"hello code in 10 fam" << endl; //endl brings us in new line 9 | } 10 | 11 | for(int i=0;i<10;i=i+1){ // this will execute 10 times 12 | cout <<"hello code in 10 fam" << endl; 13 | } 14 | return 0; 15 | } -------------------------------------------------------------------------------- /C++/Code/logicalOperators.cpp: -------------------------------------------------------------------------------- 1 | # include 2 | using namespace std; 3 | 4 | int main(){ 5 | //And gives true when all statements are true, we get false if even one is false 6 | //Or gives true if even one statement is true, we get false only if everything is false 7 | //Not, also called complement, gives opposite, so true becomes false and false becomes true 8 | 9 | bool a = true; 10 | bool b = false; 11 | 12 | cout << "a and b " << (a&&b) << endl; //0 13 | cout << "a or b " << (a||b) << endl; //1 14 | cout << "not a " << (!a) << endl; //0 15 | cout << "not b " << (!b) << endl; //1 16 | 17 | //0 means false and 1 means true 18 | 19 | } -------------------------------------------------------------------------------- /C++/Code/multipleOf2.cpp: -------------------------------------------------------------------------------- 1 | //To find multiples of 2 less than n 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | int num; 8 | cin >> num; 9 | 10 | int i = 2; 11 | for(i;i 2 | using namespace std; 3 | 4 | int main(){ 5 | int r; 6 | cin>>r; 7 | 8 | int spaces = r-1; 9 | 10 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | int r; 7 | cin>>r; 8 | 9 | int spaces = r-1; 10 | 11 | for(int i=0;i0;i--){ 24 | for(int j=0;j 2 | using namespace std; 3 | 4 | int main(){ 5 | //pre-increment 6 | //value is increased and then assigned 7 | int a = 10; 8 | int b = ++a; 9 | cout< 4 | using namespace std; 5 | 6 | int main(){ 7 | int num; 8 | cin >> num; 9 | int i = 2; 10 | for(i;i 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | int r; 7 | cin>>r; 8 | 9 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | int r; 7 | cin>>r; 8 | 9 | for(int i=0;i 8 | using namespace std; 9 | 10 | 11 | // } Driver Code Ends 12 | class Solution{ 13 | public: 14 | void reverse(int arr[], int start,int end){ 15 | while(start> t; 40 | 41 | while(t--){ 42 | int n, d; 43 | 44 | //input n and d 45 | cin >> n >> d; 46 | 47 | int arr[n]; 48 | 49 | //inserting elements in the array 50 | for(int i = 0; i < n; i++){ 51 | cin >> arr[i]; 52 | } 53 | Solution ob; 54 | //calling rotateArr() function 55 | ob.rotateArr(arr, d,n); 56 | 57 | //printing the elements of the array 58 | for(int i =0;i 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | //condition ? true : false 7 | //it is a smaller way of writing if else 8 | 9 | // so if a is 11 put c = a+1 and if a is not 11 put c=a+10 10 | //this can be done using if-else and also ternary 11 | 12 | int a=11; 13 | int c; 14 | //If else 15 | if(a==11){ 16 | c=a+1; 17 | } 18 | else{ 19 | c=a+10; 20 | } 21 | cout<<"C after if-else : "< 2 | using namespace std; 3 | 4 | int main(){ 5 | int i = 0; //in while & do while loop you must initialize a variable before hand 6 | 7 | while (i<10){ 8 | cout<<"hello code in 10 fam"< 2 | using namespace std; 3 | 4 | int main(){ 5 | int r; 6 | cin>>r; 7 | 8 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | void wall(int r,int c){ 6 | for(int i=0;i>r>>c; 17 | 18 | wall(r,c); 19 | } -------------------------------------------------------------------------------- /C++/Homework/diamond.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int e; 6 | cout<<"Enter edge length : "; 7 | cin>>e; 8 | 9 | //upper half including middle row 10 | for(int i=0;i=0;i--){ 22 | for(int k=0;k0;j--){ // for printing stars 26 | cout<<"* "; 27 | } 28 | cout< 5 | using namespace std; 6 | 7 | int main(){ 8 | //1. Using for or even while loops, Easiest logic 9 | int a[4]; 10 | for(int i=0;i<4;i++){ 11 | a[i]=4; 12 | } 13 | for(int i=0;i<4;i++){ 14 | cout< 2 | using namespace std; 3 | 4 | int productArray(int arr[], int n){ 5 | int pr=1; 6 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | void pyramid(int r){ 6 | for(int i=0;i>r; 17 | 18 | pyramid(r); 19 | } -------------------------------------------------------------------------------- /C++/Homework/sumOfArrayElements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | long long int sumArray(int arr[], int n){ 5 | long long int sm=0; 6 | for(int i=0;i= != == / . ; 27 | 28 | # Word Symbols: 29 | - Another type of token 30 | - Reserved words or keywords 31 | - **Reserved words:** Always lowercase, each considered to be single symbol with special meaning 32 | 33 | **Word Symbol Examples:** 34 | - int 35 | - float 36 | - double 37 | - char 38 | - void 39 | - return 40 | - Identifiers 41 | 42 | # Identifiers: 43 | 1. Another type of token 44 | 2. Used as names for variables, constants, and functions 45 | 3. Consist of letters, digits, and underscore character (_) 46 | 4. Must begin with letter or underscore (best not to use underscore for portability) 47 | 6. Some predefined identifiers (cout and cin) 48 | 7. Unlike reserved words, predefined identifiers may be redefined--but generally not good idea 49 | 50 | **Legal Identifier Examples:** 51 | - first 52 | - conversion 53 | - payRate 54 | 55 | **Illegal Identifier Examples:** 56 | - employee Salary (cannot use space) 57 | - Hello! (cannot use special characters, like exclamation mark) 58 | - one+two (cannot use special characters, like + character) 59 | - 2nd (cannot begin with digit) 60 | 61 | # Data Types 62 | 63 | 1. Set of values together with set of operations called data type 64 | 2. C++ data types classified into three categories: 65 | - Simple data type 66 | - Structured data type 67 | - Pointers 68 | 69 | **(A) Simple Data Types (three categories):** 70 | - **Integral:** integers (numbers without a decimal) 71 | - **Floating-point:** decimal numbers 72 | - **Enumeration type:** user-defined data type 73 | 74 | **(i) Integral Data Types (further classified):** 75 | - char 76 | - short 77 | - int 78 | - long 79 | - bool 80 | - unsigned char 81 | - unsigned short 82 | - unsigned int 83 | - unsigned long 84 | 85 | 3. Each data type associated with different set of values 86 | 4. Size of number represented determines data type 87 | 5. Data type determines amount of memory used 88 | 6. Should use most efficient data type for program requirements 89 | 7. Different compilers may have different range of values for each data type 90 | 91 | **(a) int data type:** 92 | - Numbers with no decimal point 93 | - Positive integers do not require + sign in front of them (but, can include +) 94 | - No commas are used within integer 95 | 96 | **int data type Examples:** -6728, 0, 78 97 | 98 | **(b) Bool data type:** 99 | - **Two values:** true and false, called logical (or Boolean) values 100 | - An expression that evaluates to true or false called logical (Boolean) expression 101 | - In C++, bool, true, and false are reserved words 102 | - Older compilers do not include bool data type 103 | 104 | **(c) char data type:** 105 | - Smallest integral data type 106 | - Can hold numeric values -128 to 127 107 | - **Used to represent characters:** letters, digits, and special characters 108 | - char data type can represent each character on keyboard 109 | - char data values represented within single quotation marks (e.g., 'r') 110 | - Blank is represented as ' ' (space between single quotes) 111 | 112 | **char data type Examples:** 'A', 'a', '0', '*', '+', '$', '&' 113 | 114 | **(d) Floating-Point data types:** 115 | 116 | - Represent numbers with decimal points (real numbers) 117 | - C++ uses form of scientific notation called floating-point notation 118 | - In C++, letter E (or e) represents the exponent 119 | 120 | **(i) Floating-Point data types (further classified):** 121 | 1. float 122 | 2. double 123 | 3. long double 124 | 125 | - Each data type associated with different set of values 126 | - Size of number represented determines data type 127 | - Data type determines amount of memory used 128 | 129 | **1. float :** 130 | 131 | - **Range:** -3.4E+38 to 3.4E+38 132 | - **Memory allocated:** 4 bytes 133 | - Maximum number of significant digits (decimal places) is 6 or 7 134 | - Float values called single precision 135 | 136 | **2. double data type:** 137 | - **Range:** -1.7E+308 to 1.7E+308 138 | - **Memory allocated:** 8 bytes 139 | - Maximum number of significant digits (decimal places) is 15 140 | - Double values called double precision 141 | - **Precision:** maximum number of significant digits 142 | - Should use most efficient data type for program requirements 143 | - Different compilers may have different range of values for each data type 144 | - Most newer compilers, double and long double are same 145 | 146 | **Floating-Point data type Examples:** Real Number, C++ Floating-Point Notation, 75.924, 7.592400E1 147 | 148 | **(e) string data type:** 149 | - Programmer defined data type (not included in earlier versions of C++) 150 | - To use string data type, string library must be included (include file) 151 | - Sequence of zero or more characters 152 | - Enclosed in double quotation marks (e.g., "r") 153 | - **null string:** string with no characters 154 | - Each character in string has a relative position 155 | - Position of first character is 0 (zero), 2nd character is 1, etc. 156 | - Length of string is total number of characters (e.g., "C++" length =3) 157 | -------------------------------------------------------------------------------- /C++/Notes/Contol Statements.md: -------------------------------------------------------------------------------- 1 | ### **Control Statements** 2 | --- 3 | 4 | Control statements include break and continue. These statements control the flow of execution of the program. 5 | 6 | Whenever the program encounters break, it goes out of the scope which contained break. 7 | 8 | Whenever the program encounters continue, it skips the statements after it and reaches the top of the loop/scope -------------------------------------------------------------------------------- /C++/Notes/Functions.md: -------------------------------------------------------------------------------- 1 | ### **Functions** 2 | --- 3 | 4 | - It is a piece of code that takes some input and produces some output. 5 | - It is useful when we want to do a particular calculation/processing multiple times in a program, using functions for such tasks. 6 | - This reduces the amount of lines of code we need to write & Prevents our code from becoming unnecessarily bulky. 7 | - Functions also enhance readability. 8 | - Inconsistency will occur if we want some change but don't do it at all places 9 | 10 | 11 | **Function Syntax** 12 | 13 | `return_type function_name(type input,....){` 14 | `------------------code---------------------` 15 | `-------------return output-----------------` 16 | `} ` -------------------------------------------------------------------------------- /C++/Notes/Operators.md: -------------------------------------------------------------------------------- 1 | ### **Operators** 2 | --- 3 | 4 | **Types of operators :** 5 | 1. Arithmetic Operators (Unary) : ++ , -- (these further have pre and post variants) 6 | 2. Arithmetic Operator (Binary) : +,-,/,*,% 7 | 3. Relational Operator (Binary) : <,>,<=,>=,==,!= 8 | 4. Logical Operators (Binary) : &&,||,! 9 | 5. Bitwise Operators (Binary) : &,|,<<,>>,~,^ 10 | 6. Assignment Operator : =,+=,-=,*=,/= 11 | 7. Conditional Operator (Ternary) : ?: -------------------------------------------------------------------------------- /C++/Notes/Pattern Printing.md: -------------------------------------------------------------------------------- 1 | ### **Pattern Printing** 2 | --- 3 | 4 | **Main concepts used in these problems :** 5 | 1. For loop 6 | 2. While loop 7 | 3. break 8 | 4. continue 9 | 5. operators 10 | 11 | NOTE : These problems are generally simple but they do have variations that can be tricky -------------------------------------------------------------------------------- /C++/Notes/XOR.md: -------------------------------------------------------------------------------- 1 | ### **XOR** 2 | --- 3 | 4 | Brute Force solution is the simplest approach that we try when it first comes to our mind. 5 | It is just a first idea, and therefore is mostly not the best way to solve the problem. 6 | 7 | To solve this problem the brute force approach will be to count how many times each element occurs 8 | and store this data in some other array, but this will take more time and space 9 | 10 | So an optimized approach will be to use XOR operation, this operation fives 0 if 2 elements are different 11 | and 1 if both are different 12 | Also, 13 | n^n = 0 14 | n^0 = n -------------------------------------------------------------------------------- /C++/Notes/conditionals.md: -------------------------------------------------------------------------------- 1 | ### **Conditionals** 2 | 3 | --- 4 | 5 | Conditionals refer to if-else and switch 6 | these are used to choose between multiple options, just like in real life we many times have to choose between multiple options, based on the condition we are in 7 | if-else and switch do the similar thing but in code 8 | Some examples of such problems can be program to check eligibility to vote based on age, FizzBuzz problem 9 | FizzBuzz is a problem in which we print Fizz if number is divisible by 3 and print Buzz if its divisible by 5 10 | 11 | **If-else Syntax** 12 | `if (Condition){ ` 13 | `----Thing to do----` 14 | `} else { ` 15 | `--Else what to do--` 16 | `} ` 17 | 18 | **Switch Syntax** 19 | `switch(expression){` 20 | `case const1: ` 21 | `---things to do----` 22 | ` break; ` 23 | `case const2: ` 24 | `---things to do----` 25 | ` break; ` 26 | `default: ` 27 | ` break; ` 28 | `} ` 29 | 30 | switch case is more cleaner, but mostly people prefer using if-else -------------------------------------------------------------------------------- /C++/Notes/datatypes.md: -------------------------------------------------------------------------------- 1 | ### **Data-Types in C++** 2 | 3 | --- 4 | 5 | 6 | 7 | **3 Types of Data-types in C++ :** 8 | 9 | 1. Primary : these are predefined data-types that can be used directly (Example : int,void,floating point,double floating point,Boolean,character) 10 | 2. Derived : these data types or data structures that are derived from the basic data types (Example : Function, Array, Pointer, Reference) 11 | 3. User Defined : These are the data types that are created by the user and are not pre defined (Example : Class, Structure, Union, Enum, Typedef) 12 | 13 | 14 | 15 | Data-types are used to store/save variables or constants 16 | 17 | Variable is something whose value can be changed in future 18 | 19 | Constants are those values that can not be changed later on 20 | 21 | Whenever we declare/initialize a variable we use the following syntax 22 | `data_type variable_name = value ; ` 23 | or 24 | `data_type variable_name ; ` 25 | `variable_name = value ; ` 26 | 27 | To store multiple such values we don't create tens or hundreds or new variables, instead we make use of arrays, which is a derived data-type/data structure and is used to store multiple values linearly in contiguous location -------------------------------------------------------------------------------- /C++/Notes/explaination.md: -------------------------------------------------------------------------------- 1 | ### **First Program Explanation Line by line** 2 | 3 | 1. `#include` is the pre processor directive 4 | By pre processor directive we mean that this is executed first before anything else in the program occurs 5 | What include does is that it includes the file we specified in the program, so that its functions can be directly used later on in the main program 6 | 7 | 2. `` is the file that we have to include for performing i/o or input/output 8 | so this is necessary to take input from user & produce output to the screen 9 | If we don't include this we get an error because program doesn't know what cin & cout are, and will become incapable of handling i/o 10 | 11 | 3. `using namespace std;` 12 | std is the namespace where we have pre-written definitions and declaration of stuff 13 | So in other words it's like a dictionary for the program so that it can understand the default names 14 | `using` is to make sure that the whole program follows the standard std; 15 | alternatively if we don't want to write the whole statement we can write `std::` before every function 16 | we can also create our own custom namespace if we want to 17 | 18 | 4. `int main()` 19 | int is a data type and main is a function 20 | main() function is like the top manager of a C++ program & it is where the execution of the program starts 21 | without main a function won't even run 22 | Note : You can not name main something else like "major","important",etc. main must be called main only 23 | 24 | 5. `cout<<` is used to print the output to the screen 25 | `cin>>` is for taking input from the user via keyboard 26 | 27 | 6. `"Hello Code in 10 Fam"` is a string 28 | a string is used for writing a sentence or line of characters 29 | 30 | 7. `;` is used at the end of all statements in C++, except for certain things like including pre-processor, etc. 31 | 32 | 8. `return 0;` returns at the end of the program 33 | in newer versions of C++ compilers it is mostly optional 34 | 35 | 9. `{}` define the scope of the functions/classes,etc. used -------------------------------------------------------------------------------- /C++/Notes/loops.md: -------------------------------------------------------------------------------- 1 | ### **Loops** 2 | --- 3 | 4 | **Definition :** It is a set of instructions that is executed continuously until a certain condition is reached. In other words, it works as long as the condition provided to it continues to be true. 5 | 6 | these are used to reduce the code required for completing actions that are required to be performed continuously n number of times, such as printing "hello" 100 times can be done in 4 to 5 lines with loops otherwise it would have taken 100 lines 7 | 8 | **3 Types of loops in C++** 9 | 1. For loop (mostly used for fixed number of iterations) 10 | 2. While loop (mostly used if number of iterations is not known beforehand) 11 | 3. Do-while loop (used for same reason as while, but it being an exit controlled loop it executes at least once no matter whether the condition is true or false. It will execute one time at least) 12 | 13 | **For Syntax** 14 | `for(initialize;condition;increment/decrement){` 15 | `---------------tasks to do--------------------` 16 | `} ` 17 | 18 | **While Syntax** 19 | `while(condition){ ` 20 | `----tasks to do----` 21 | `increment/decrement` 22 | `} ` 23 | 24 | **Do-while Syntax** 25 | `do{ ` 26 | `----tasks to do----` 27 | `increment/decrement` 28 | `} while(Condition);` 29 | 30 | **Note :** 31 | 1. while and do while don't initialize a variable so we must have a variable initialized beforehand to use these 32 | 2. Variables have scopes so a variable that is defined inside a function can be used by that function only, like the variable initialized by for inside a bracket will only be used inside the for loop and not outside -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CodeIn10DSA 2 | 3 | This Repo will be used to post notes and solutions to all the problems discussed on the channel Code In 10. 4 | 5 | Link: https://www.youtube.com/channel/UClYcYuuwLqTPmH74-xRxZhQ 6 | -------------------------------------------------------------------------------- /Recursion/Code/NthStair.c: -------------------------------------------------------------------------------- 1 | //Program to find the number of ways to reach the nth stair 2 | #include 3 | 4 | int countWays(int n){ 5 | if (n==1 || n==2){ 6 | return n; 7 | } 8 | else{ 9 | return countWays(n-1)+countWays(n-2); 10 | } 11 | } 12 | 13 | int main(){ 14 | int N; 15 | printf("Enter a positive number : "); 16 | scanf("%d",&N); 17 | printf("Number of ways to reach %d",N); 18 | printf("th Stair are = %d\n",countWays(N)); 19 | } -------------------------------------------------------------------------------- /Recursion/Code/NthStair.cpp: -------------------------------------------------------------------------------- 1 | //Program to find the number of ways to reach the nth stair 2 | #include 3 | using namespace std; 4 | int countWays(int n){ 5 | if (n==1 || n==2){ 6 | return n; 7 | } 8 | else{ 9 | return countWays(n-1)+countWays(n-2); 10 | } 11 | } 12 | int main(){ 13 | int N; 14 | cout<<"Enter a positive number : "; 15 | cin>>N; 16 | cout<<"Number of ways to reach "<>S; 28 | 29 | sequence(S,"",0); 30 | cout< 5 | long long int factorial(int n) { 6 | 7 | if (n==0 || n==1){ //Base Case 8 | return 1; 9 | } 10 | 11 | else{ 12 | //return n * factorial(n-1) one way 13 | //other way 14 | 15 | int recResult = factorial(n-1); // Recursive Call 16 | int result = n*recResult; // Small Calculation 17 | return result; 18 | } 19 | } 20 | 21 | int main(){ 22 | 23 | int N; 24 | printf("Enter a number whose factorial we need : "); 25 | scanf("%d",&N); 26 | 27 | printf("Factorial of %d",N); 28 | printf(" is = %lld \n",factorial(N)); 29 | } 30 | -------------------------------------------------------------------------------- /Recursion/Code/factorials.cpp: -------------------------------------------------------------------------------- 1 | // Recursion 2 | // Factorial of number n 3 | 4 | #include 5 | using namespace std; 6 | 7 | long long int factorial(int n) { //Base Case 8 | 9 | if (n==0 || n==1){ 10 | return 1; 11 | } 12 | 13 | else{ 14 | //return n * factorial(n-1) one way 15 | //other way 16 | 17 | int recResult = factorial(n-1); // Recursive Call 18 | int result = n*recResult; // Small Calculation 19 | return result; 20 | } 21 | } 22 | 23 | int main(){ 24 | 25 | int N; 26 | cout<<"Enter a number whose factorial we need : "; 27 | cin>>N; 28 | 29 | cout<<"Factorial of "< 4 | 5 | using namespace std; 6 | 7 | int fibonacci(int n){ 8 | if (n==0){ //Base Case 1 9 | return 0; 10 | } 11 | else if (n==1){ //Base Case 2 12 | return 1; 13 | } 14 | else{ 15 | return fibonacci(n-1)+fibonacci(n-2); //fibonacci(n-1) and fibonacci(n-2) are recursive calls 16 | //addition of the two is our small calculation 17 | } 18 | 19 | } 20 | 21 | int main(){ 22 | int n; 23 | cout<<"Enter a non-negative number : "; 24 | cin>>n; 25 | cout<<"nth Fibonacci number is : "< 2 | #include 3 | 4 | using namespace std; 5 | 6 | int helper(string S, int start, int end){ 7 | if (start>=end){ 8 | return 1; 9 | } 10 | if(S[start]!=S[end]){ 11 | return 0; 12 | } 13 | return helper(S, start+1, end-1); 14 | } 15 | 16 | int isPalindrome(string S) 17 | { 18 | int n=S.size()-1; 19 | return helper(S,0,n); 20 | } 21 | 22 | int main(){ 23 | string s; 24 | cout<<"Enter a string : "; 25 | cin>>s; 26 | int result = isPalindrome(s); 27 | if (result == 1){ 28 | cout<<"String is palindrome"<=end: 3 | return 1 4 | if (S[start]!=S[end]): 5 | return 0; 6 | return helper(S,start+1,end-1) 7 | 8 | def isPalindrome(S): 9 | n=len(S)-1 10 | return helper(S,0,n) 11 | 12 | s=input("Enter a String : ") 13 | result=isPalindrome(s) 14 | 15 | if result==1: 16 | print("String is palindrome") 17 | else: 18 | print("String is NOT palindrome") -------------------------------------------------------------------------------- /Recursion/Code/powerOf2.c: -------------------------------------------------------------------------------- 1 | //Program to calculate 2 raised to the power n 2 | 3 | #include 4 | 5 | int power(int n){ 6 | if (n==1){ //Base Case 7 | return 2; 8 | } 9 | else{ 10 | return 2*power(n-1); //multiplication with 2 is small calculation & power(n-1) is the recursive call 11 | } 12 | } 13 | 14 | int main() { 15 | int n; 16 | printf("Enter a positive number : "); 17 | scanf("%d",&n); 18 | printf("2^%d",n); 19 | printf(" = %d\n",power(n)); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Recursion/Code/powerOf2.cpp: -------------------------------------------------------------------------------- 1 | //Program to calculate 2 raised to the power n 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | int power(int n){ 8 | if (n==1){ //Base Case 9 | return 2; 10 | } 11 | else{ 12 | return 2*power(n-1); //multiplication with 2 is small calculation & power(n-1) is the recursive call 13 | } 14 | } 15 | 16 | int main() { 17 | int n; 18 | cout<< "Enter a positive number : "; 19 | cin>>n; 20 | cout<<"2^"<> n; 47 | 48 | vector array; 49 | for (int i = 0; i < n; i++) 50 | { 51 | cin >> x; 52 | array.push_back(x); 53 | } 54 | 55 | 56 | Solution ob; 57 | vector > res = ob.subsets(array); 58 | 59 | // Print result 60 | cout< 5 | 6 | int sumN(int n){ //Base Case 7 | 8 | if (n==1){ 9 | return 1; 10 | } 11 | 12 | else{ 13 | return n+sumN(n-1); // sumN(n-1) is recursive call 14 | // and n + sumN(n-1) is our small calculation 15 | } 16 | } 17 | 18 | int main(){ 19 | 20 | int n; 21 | printf("Enter a positive number n : "); 22 | scanf("%d",&n); 23 | 24 | printf("Sum of first n natural numbers = %d \n",sumN(n)); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Recursion/Code/sumFirstN.cpp: -------------------------------------------------------------------------------- 1 | // Recursion 2 | // Sum of first n natural numbers 3 | 4 | #include 5 | using namespace std; 6 | 7 | int sumN(int n){ 8 | if (n==1){ //Base Case 9 | return 1; 10 | } 11 | 12 | else{ 13 | return n+sumN(n-1); // sumN(n-1) is recursive call 14 | // and n + sumN(n-1) is our small calculation 15 | } 16 | } 17 | 18 | int main(){ 19 | 20 | int n; 21 | cout<<"Enter a positive number n : "; 22 | cin>>n; 23 | 24 | cout<<"Sum of first n natural numbers = "< AllPossibleStrings(string s){ 25 | vector ans; 26 | helper(s,"",0); 27 | return ans; 28 | // Code here 29 | } 30 | }; 31 | 32 | // { Driver Code Starts. 33 | int main(){ 34 | int tc; 35 | cin >> tc; 36 | while(tc--){ 37 | string s; 38 | cin >> s; 39 | Solution ob; 40 | vector res = ob.AllPossibleStrings(s); 41 | for(auto i : res) 42 | cout << i <<" "; 43 | cout << "\n"; 44 | 45 | } 46 | return 0; 47 | } // } Driver Code Ends 48 | -------------------------------------------------------------------------------- /Recursion/Homework/Subsets.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | class Solution 12 | { 13 | 14 | public: 15 | 16 | vector > ans; //Global Variable 17 | //vector is a Dynamic Data structure similar to array but unlike array we do not need to declare its size in advance 18 | 19 | void helper(vector A,vectortemp, int i){ 20 | if (i==A.size()){ //Base Case 21 | ans.push_back(temp); //this will keep the contents of temp in ans for now 22 | return; 23 | } 24 | 25 | temp.push_back(A[i]); //Appends or adds element at the end 26 | helper(A,temp,i+1); //Inclusion or Take condition 27 | 28 | temp.pop_back(); //Removes an element from the end 29 | helper(A,temp,i+1); //Exclusion or not-take condition 30 | 31 | return; 32 | } 33 | 34 | vector > subsets(vector& A) 35 | { 36 | //code here 37 | vector temp; 38 | helper(A,temp,0); 39 | sort(ans.begin(),ans.end()); //this is to sort the array 40 | return ans; 41 | } 42 | 43 | }; 44 | 45 | 46 | // { Driver Code Starts. 47 | 48 | int main() 49 | { 50 | int t; 51 | cin >> t; 52 | 53 | while (t--) 54 | { 55 | int n, x; 56 | cin >> n; 57 | 58 | vector array; 59 | for (int i = 0; i < n; i++) 60 | { 61 | cin >> x; 62 | array.push_back(x); 63 | } 64 | 65 | 66 | Solution ob; 67 | vector > res = ob.subsets(array); 68 | 69 | // Print result 70 | for (int i = 0; i < res.size(); i++) { 71 | for (int j = 0; j < res[i].size(); j++) 72 | cout << res[i][j] << " "; 73 | cout << endl; 74 | } 75 | 76 | 77 | } 78 | 79 | return 0; 80 | } // } Driver Code Ends 81 | -------------------------------------------------------------------------------- /Recursion/Homework/factorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | long long int factorial(int N){ 7 | // Base Case 8 | if (N == 1 || N == 0){ 9 | return 1; 10 | } 11 | 12 | // Recursive Call 13 | long long int recResult = factorial(N-1); 14 | 15 | // Small Calculation 16 | long long int result = N*recResult; 17 | 18 | return result; 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | int t; 25 | cin>>t; 26 | while(t--) 27 | { 28 | int N; 29 | cin>>N; 30 | Solution ob; 31 | cout << ob.factorial(N) << endl; 32 | } 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Recursion/Homework/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | long long int nthFibonacci(long long int n){ 7 | // code here 8 | 9 | // Base Case 10 | if (n == 0) { 11 | return 0; 12 | } 13 | 14 | if (n == 1){ 15 | return 1; 16 | } 17 | 18 | // Recursive Call 19 | long long int recCall1 = nthFibonacci(n-1); 20 | long long int recCall2 = nthFibonacci(n-2); 21 | 22 | // Small Calculation 23 | long long int smallCal = recCall1 + recCall2; 24 | 25 | return smallCal; 26 | 27 | } 28 | }; 29 | 30 | int main() { 31 | int t; 32 | cin >> t; 33 | while (t--) { 34 | long long int n; 35 | cin >> n; 36 | Solution ob; 37 | cout << ob.nthFibonacci(n) << endl; 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Recursion/Homework/nthStair.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | int countWays(int n) 7 | { 8 | //code here 9 | 10 | //Base Case 11 | if (n==1 || n==2){ 12 | return n; 13 | } 14 | 15 | // Recursive Call 16 | int recCall1 = countWays(n-1); 17 | int recCall2 = countWays(n-2); 18 | 19 | // Small Calculation 20 | int smallCal = recCall1 + recCall2; 21 | 22 | return smallCal; 23 | } 24 | }; 25 | 26 | 27 | 28 | int main() 29 | { 30 | int t; 31 | cin >> t; 32 | while(t--) 33 | { 34 | int m; 35 | cin>>m; 36 | Solution ob; 37 | cout< 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | //User function template for C++ 9 | class Solution{ 10 | public: 11 | int helper(string S, int start, int end){ 12 | if (start>=end){ 13 | return 1; 14 | } 15 | if(S[start]!=S[end]){ 16 | return 0; 17 | } 18 | return helper(S, start+1, end-1); 19 | } 20 | 21 | int isPalindrome(string S) 22 | { 23 | // Your code goes here 24 | int n=S.size()-1; 25 | return helper(S,0,n); 26 | } 27 | 28 | }; 29 | 30 | // { Driver Code Starts. 31 | 32 | int main() 33 | { 34 | ios_base::sync_with_stdio(0); 35 | cin.tie(NULL); 36 | cout.tie(NULL); 37 | 38 | int t; 39 | cin >> t; 40 | while(t--) 41 | { 42 | string s; 43 | cin >> s; 44 | 45 | Solution ob; 46 | 47 | cout << ob.isPalindrome(s) << "\n"; 48 | } 49 | 50 | return 0; 51 | } // } Driver Code Ends -------------------------------------------------------------------------------- /Recursion/Homework/permutations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> ans; 4 | void helper(vector & nums, int i){ 5 | if (i==nums.size()){ // Base Case 6 | ans.push_back(nums); 7 | return; 8 | } 9 | for (int j=i;j> permute(vector& nums) { 19 | helper(nums,0); 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Recursion/Homework/possibleWordsFromPhone.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | // } Driver Code Ends 11 | //User function Template for C++ 12 | 13 | class Solution 14 | { 15 | public: 16 | vector keys = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 17 | vector ans; 18 | //Function to find list of all words possible by pressing given numbers. 19 | void helper(int a[],int n,string temp,int i){ 20 | if (i==n){ 21 | ans.push_back(temp); 22 | return; 23 | } 24 | for (int j=0;j possibleWords(int a[], int N) 29 | { 30 | //Your code here 31 | helper(a,N,"",0); 32 | return ans; 33 | } 34 | }; 35 | 36 | 37 | // { Driver Code Starts. 38 | 39 | int main() { 40 | 41 | int T; 42 | 43 | cin >> T; //testcases 44 | 45 | while(T--){ //while testcases exist 46 | int N; 47 | 48 | cin >> N; //input size of array 49 | 50 | int a[N]; //declare the array 51 | 52 | for(int i =0;i> a[i]; //input the elements of array that are keys to be pressed 54 | } 55 | 56 | Solution obj; 57 | 58 | vector res = obj.possibleWords(a,N); 59 | for (string i : res) cout << i << " "; 60 | cout << endl; 61 | } 62 | 63 | return 0; 64 | } // } Driver Code Ends 65 | -------------------------------------------------------------------------------- /Recursion/Homework/reverse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int n; 4 | void helper(int* s,int start,int end){ 5 | if (start>=end){ 6 | for (int i=0;i>t; 21 | while(t--){ 22 | cin>>n; 23 | int s[n]; 24 | for (int i=0;i>s[i]; 26 | } 27 | helper(s,0,n-1); 28 | //code 29 | } 30 | return 0; 31 | } -------------------------------------------------------------------------------- /Recursion/Homework/subsetSum.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | //User function template for C++ 9 | 10 | class Solution{ 11 | public: 12 | bool helper (vector a, int sum,int tempSum, int i){ 13 | //Base Cases 14 | if (sum==tempSum){ 15 | return true; 16 | } 17 | if (i>=a.size()){ 18 | return false; 19 | } 20 | 21 | //Recursive Calls 22 | int recCall1 = helper(a,sum,tempSum+a[i],i+1); 23 | int recCall2 = helper(a,sum,tempSum,i+1); 24 | 25 | //Small Calculation 26 | return recCall1 || recCall2; 27 | 28 | } 29 | bool isSubsetSum(vectorarr, int sum){ 30 | return helper(arr,sum,0,0); 31 | // code here 32 | } 33 | }; 34 | 35 | // { Driver Code Starts. 36 | int main() 37 | { 38 | int t; 39 | cin>>t; 40 | while(t--) 41 | { 42 | int N, sum; 43 | cin >> N; 44 | vector arr(N); 45 | for(int i = 0; i < N; i++){ 46 | cin >> arr[i]; 47 | } 48 | cin >> sum; 49 | 50 | Solution ob; 51 | cout << ob.isSubsetSum(arr, sum) << endl; 52 | } 53 | return 0; 54 | } 55 | // } Driver Code Ends 56 | -------------------------------------------------------------------------------- /Recursion/Notes/Recursion Notes - Day 1.md: -------------------------------------------------------------------------------- 1 | # Recursion 2 | - A function calling itself is called recursion 3 | - In recursion we break bigger problem into smaller problem, and use recursion to solve those smaller problems and finally get a desired output, This is known as 'Recursion Leap of Faith' 4 | 5 | --- 6 | 7 | [Question_1] : Sum of first n natural numbers using recursion 8 | 9 | [Logic] : sum of first n numbers = n + sum of (n-1) numbers, sum of first (n-1) numbers = (n-1) + sum of (n-2) numbers and so on, in this case the base condition should be for n = 1 10 | 11 | [Flow_Example] : 12 | sumN(4)=4 + sumN(3) = 4 + 3 + sumN(2) = 4 + 3 + 2 + sumN(1) = 4 + 3 + 2 + 1 = 10 13 | 14 | Note : Every recursion has a Base Case which prevents it from continuing indefinitely 15 | 16 | ## 3 Parts of Recursion 17 | 1. Base Case 18 | 2. Small Calculation 19 | 3. Recursive formula 20 | 21 | small calculation and recursive formula are interchangeable and one can come before the other 22 | 23 | - Most important part is Recursive Call and then at 2nd comes the Base case 24 | 25 | --- 26 | 27 | [Question_2] : Find Factorial of number n 28 | 29 | [Logic] : factorial of number n = n * factorial of number (n-1), factorial of number (n-1) = (n-1) * factorial of number (n-2) and so on, in this case the base condition should be for n = 1 and n = 0, factorial of both is 1 30 | 31 | [Flow_Example] : 32 | factorial(4)=4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * factorial(1) = 4 * 3 * 2 * 1 = 24 33 | -------------------------------------------------------------------------------- /Recursion/Notes/Recursion Notes - Day 2.md: -------------------------------------------------------------------------------- 1 | # Recursive Tree 2 | 3 | It is the pictorial/graphical representation of a recursion. It is used to solve and/or better understand a recursive pattern. 4 | 5 | **Question :** Program to calculate 2n , n starts from 1 6 | 7 | **Logic :** 24 = 2 * 23 = 2 * 2 * 22 = 2 * 2 * 2 * 2 = 2 * 2 * 4 = 2 * 8 = 16 8 | 9 | Therefore we can say that we can write :- 10 | 11 | F(n) = 2*F(n-1) This is our recursive call 12 | 13 | This question utilizes a "Linear recursive tree". 14 | 15 | --- 16 | 17 | ### Fibonacci Series 18 | 19 | **Question :** Program to find nth term of a Fibonacci series 20 | 21 | **Logic :** Fibonacci series is a series of numbers in which each number is the sum of the two preceding numbers 22 | 23 | It goes as : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... 24 | 25 | *Formula :* F(n) = F(n-1) + F(n-2) where F(0)=0 and F(1)=1 and "n" is non-negative 26 | 27 | *Sample :* 28 | 29 | F(4) = F(3) + F(2) 30 | 31 | F(3) = F(2) +F(1) 32 | 33 | F(2) =F(1) +F(0) 34 | 35 | since F(1) is 1 and F(0) is 0, so F(2) = 1 + 0 =1 36 | 37 | F(3) = F(2) + F(1) = 1 + 1 = 2 38 | 39 | F(4) = F(3) + F(2) = 2 +1 =3 40 | 41 | Hence, This program uses a more "branched/non-linear recursive tree" 42 | -------------------------------------------------------------------------------- /Recursion/Notes/Recursion Notes - Day 3.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | ### Revision 4 | 5 | **3 Basic Steps of Recursion:** 6 | 7 | 1. Base Case 8 | 9 | 2. Recursive Call 10 | 11 | 3. Small Calculation 12 | 13 | --- 14 | 15 | ### Count Ways to Reach Nth Stair Problem : 16 | 17 | 18 | 19 | **Question :** Count Ways to Reach Nth Stair (person only jumps 1 or 2 stairs at a time) 20 | 21 | **Logic :** suppose we have to reach on top of 6 stairs, now there are multiple ways to do it: 22 | 23 | 1st is to go 1 stair at a time, 2nd way is to jump 2 stairs at first and then 1 at a time, 3rd might be to go first 1 stair then 2 stair and so on... 24 | 25 | so, we have **Multiple Cases** 26 | 27 | Since the maximum stairs that we can jump is 2; so the number of ways to reach the top stair are equal to sum ways of reaching the previous 2 stairs 28 | 29 | **NOTE : This part is quite similar to the Fibonacci Series** 30 | 31 | **Recursive call :** F(n) = F(n-1) + F(n-2)                Same as Fibonacci 32 | 33 | BUT there is a difference and it is in the base case 34 | 35 | In Fibonacci base cases were : F(0) = 0 and F(1) = 1 36 | 37 | & Here in nth stair base cases are : F(1) = 1 and F(2) = 2 38 | 39 | **Reason for this :** If you have just one stair and you are on the ground there is just one way to reach the 1 stair and that is to jump one stair. If you have 2 stairs then you have 2 ways: First is that you jump 1 stair to reach 1st stair and then again jump one more stair to reach 2nd stair. Second way is to directly jump 2 stairs since that is the max we are allowed to jump at once. 40 | 41 | 42 | 43 | And just as Fibonacci series even this question results in a **non-linear branched Recursive Tree** very similar to the one in Fibonacci. 44 | 45 | --- 46 | 47 | **Final Note :** This question actually belongs to Dynamic Programming (DP) and therefore recursion is not the most efficient way to do it. 48 | 49 | --- 50 | -------------------------------------------------------------------------------- /Recursion/Notes/Recursion Notes - Day 4.md: -------------------------------------------------------------------------------- 1 | ### Recap 2 | 3 | **3 main steps :** 4 | 5 | 1. Base Case 6 | 7 | 2. Recursive Call 8 | 9 | 3. Small Calculation 10 | 11 | --- 12 | 13 | **QUESTION 1 :** Write a program to check if a string is palindrome or not using recursion 14 | 15 | **LOGIC :** Palindrome is string/word that reads the same from left to right and right to left 16 | 17 | - Examples : madam, noon, mam, .... 18 | 19 | 20 | 21 | **2 Main Approach :** 22 | 23 | 1. Go from left to right and compare it with right to left 24 | 25 | 2. using recursion by checking symmetry around middle letter 26 | 27 | 28 | 29 | So for this we take a sample word **abcba** so we have to start with first index 0 and increase it continuously and also take an ending index (length - 1) and decrease it continuously while checking the two, until both become same index. 30 | 31 | 32 | 33 | **For abcba** 34 | 35 | s=0 , e= 4 --> we check is string[0] == string[4] answer comes yes so we continue 36 | 37 | next, s=1 , e=3 --> we check is string[1] == string[3] answer comes yes so we continue 38 | 39 | now finally s == e so we are in middle so base case is reached and function completes 40 | 41 | 42 | 43 | **For nishan** 44 | 45 | s=0 , e=5 --> we check is string[0] == string[5] answer comes yes so we continue 46 | 47 | next, s=1 , e=4 --> we check is string[1] == string[4] answer comes NO so we exit 48 | 49 | --- 50 | 51 | **QUESTION 2 :** Write a program to reverse an array using recursion 52 | 53 | **Logic :** similar to question 1 but instead of checking whether they are equal or not we actually have to swap the two values until start becomes greater than or equal to end. 54 | -------------------------------------------------------------------------------- /Recursion/Notes/Recursion Notes - Day 5.md: -------------------------------------------------------------------------------- 1 | ### Subsequence 2 | 3 | **sub sequence is a part of a sequence** 4 | 5 | example : in string "ajk" -> we have sub-sequences "a","j","k","aj","jk","ajk" and null/nothing 6 | 7 | These can be **Continuous or non-continuous**, which is unlike substring or sub arrays which are always "continuous" 8 | 9 | example : in number 1,2,3,4,5,6    => 1,2,3,4 can be a subarray/subsequence 10 | 11 | however, 1,2,3,5 is strictly a subsequence since it is not continuous 12 | 13 | ---- 14 | 15 | **QUESTION :** Find all possible subsequences of a string 16 | 17 | **Note :** Power Set does not include "empty" string 18 | 19 | **LOGIC :** 20 | 21 | 2 main conditions : 22 | 23 | - Take (a condition in which we are including a particular element is known as take) 24 | 25 | - Not Take (condition where a particular element is not included is called not take) 26 | 27 | Here we will be taking care of 3 main things : 28 | 29 | - Given String 30 | 31 | - current temporary answer 32 | 33 | - current index, i 34 | 35 | **Base condition :** string size is equal to index 36 | 37 | **Helper Function :** When we need some extra parameters then we create a helper function similar to our primary function, to deal with extra values 38 | 39 | ---- 40 | -------------------------------------------------------------------------------- /Recursion/Notes/Recursion Notes - Day 6.md: -------------------------------------------------------------------------------- 1 | ### Subsets 2 | 3 | **** 4 | 5 | **Approach :** Similar to subsequences, Subsets also utilize take & not take conditions (inclusion and exclusion) and has a branched non-linear tree structure 6 | 7 | We need to take care of 3 main things : 8 | 9 | - Current array 10 | 11 | - Temporary array 12 | 13 | - Index, i 14 | 15 | Total number of subsets = 2n (because at each stage we had 2 choices take & not-take) 16 | -------------------------------------------------------------------------------- /Recursion/Notes/Recursion Notes - Day 7.md: -------------------------------------------------------------------------------- 1 | ---- 2 | 3 | ### Subset Sum Problem 4 | 5 | **3 basic parts of recursion :** 6 | 7 | 1. Base Case 8 | 9 | 2. Recursive Call 10 | 11 | 3. Small Calculation 12 | 13 | **Note :** In all questions involving Subsets and sequences we use inclusion/exclusion or take/not-take conditions if solved via recursion 14 | 15 | **QUESTION :** Given an array of non-negative integers, and a value *sum*, determine if there is a subset of the given set with sum equal to given *sum*. 16 | 17 | **LOGIC :** 18 | 19 | 3 main things to take care of : 20 | 21 | 1. Array 22 | 23 | 2. Current Sum 24 | 25 | 3. Index 26 | 27 | **NOTE :** To check whether or not even one condition is true, we use *logical OR operation* 28 | 29 | this is because 30 | 31 | true Or true = true 32 | 33 | true Or false = true 34 | 35 | false Or true = true 36 | 37 | false Or false = false 38 | 39 | So even if one case is true we will always get true, just as required 40 | 41 | Rest of the execution is logic is similar to Day 6's problem with the only difference being that instead of taking subsets, we are taking sum of those subsets and checking whether or not they are equal to the required sum. 42 | 43 | ---- 44 | -------------------------------------------------------------------------------- /Recursion/Notes/Recursion Notes - Day 8.md: -------------------------------------------------------------------------------- 1 | ### Permutations 2 | 3 | It refers to **the number of ways** we can **arrange something** 4 | 5 | Example: if we have 3 elements [1,2,3] then we have 3 possibilities for 1st place, 2 for 2nd place and 1 possibility for last place. 6 | 7 | Formula : n!/(n!-r!) but here since all objects are selected at all times, therefore 8 | 9 | formula = n! only 10 | 11 | 12 | 13 | here we will be using **count array**, this might require a bit more space since we are using an extra array but its a fairly simple approach 14 | 15 | 16 | A more optimized approach will be to find all possible swaps of the final array 17 | 18 | we will do this by swapping the elements on the right of current index 19 | -------------------------------------------------------------------------------- /Recursion/Notes/Recursion Notes - Day 9.md: -------------------------------------------------------------------------------- 1 | ### Possible Words from Phone Digit 2 | 3 | Given a keypad as shown in the diagram, and an **N** digit number which is represented by array **a[ ]**, the task is to list all words which are possible by pressing these numbers. 4 | 5 | 6 | 7 | So in this question we must keep in mind the layout of older 2G phones, and the way text was present over those buttons 8 | 9 | 10 | 11 | **Logic :** similar to yesterday 12 | -------------------------------------------------------------------------------- /Sorting/Code/mergeSort.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector merge(vector &A, vector& B){ 4 | int sizeA=A.size(); 5 | int sizeB=B.size(); 6 | int i=0; 7 | int j=0; 8 | vector ans; 9 | 10 | //Compare and fill ans vector 11 | while (i mergeSort(vector& nums,int start, int end) { 38 | //Base Case 39 | if (start>end){ 40 | return {}; 41 | } 42 | if (start==end){ 43 | return {nums[start]}; 44 | } 45 | 46 | //Calculate Mid 47 | int mid= start+(end-start)/2; 48 | 49 | //MergeSortCall 50 | vector A = mergeSort(nums,start,mid); 51 | vector B = mergeSort(nums,mid+1,end); 52 | 53 | //MergeCall 54 | return merge(A,B); 55 | } 56 | 57 | vector sortArray(vector& nums) { 58 | int n=nums.size(); 59 | return mergeSort(nums,0,n-1); 60 | } 61 | }; -------------------------------------------------------------------------------- /Sorting/Code/mergeSort.py: -------------------------------------------------------------------------------- 1 | def merge_sort(arr): 2 | if len(arr) <= 1: 3 | return 4 | 5 | mid = len(arr)//2 6 | 7 | left = arr[:mid] 8 | right = arr[mid:] 9 | 10 | merge_sort(left) 11 | merge_sort(right) 12 | 13 | merge_two_sorted_lists(left, right, arr) 14 | 15 | def merge_two_sorted_lists(a,b,arr): 16 | len_a = len(a) 17 | len_b = len(b) 18 | 19 | i = j = k = 0 20 | 21 | while i < len_a and j < len_b: 22 | if a[i] <= b[j]: 23 | arr[k] = a[i] 24 | i+=1 25 | else: 26 | arr[k] = b[j] 27 | j+=1 28 | k+=1 29 | 30 | while i < len_a: 31 | arr[k] = a[i] 32 | i+=1 33 | k+=1 34 | 35 | while j < len_b: 36 | arr[k] = b[j] 37 | j+=1 38 | k+=1 39 | 40 | if __name__ == '__main__': 41 | nums = [ 42 | [5,2,3,1], 43 | [5,1,1,2,0,0] 44 | ] 45 | 46 | for arr in nums: 47 | merge_sort(arr) 48 | print(arr) -------------------------------------------------------------------------------- /Sorting/Code/quickSort.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C 3 | 4 | #include 5 | 6 | /* Function to print an array */ 7 | void printArray(int arr[], int size) 8 | { 9 | int i; 10 | for (i=0; i < size; i++) 11 | printf("%d ", arr[i]); 12 | printf("\n"); 13 | } 14 | 15 | // } Driver Code Ends 16 | //User function Template for C 17 | void swap(int *nums,int i,int j){ 18 | int temp = nums[i]; 19 | nums[i]=nums[j]; 20 | nums[j]=temp; 21 | } 22 | //Function to sort an array using quick sort algorithm. 23 | void quickSort(int arr[], int start, int end) 24 | { 25 | // code here 26 | if (start pivot: 24 | end-=1 25 | 26 | if start < end: 27 | swap(start, end, elements) 28 | 29 | swap(pivot_index, end, elements) 30 | 31 | return end 32 | 33 | 34 | if __name__ == '__main__': 35 | N = int(input("Enter the number of elements to be sorted:")) 36 | elements = [] 37 | for i in range(0,N): 38 | ele = int(input("Enter Elements of Array:")) 39 | elements.append(ele) 40 | quick_sort(elements, 0, len(elements)-1) 41 | print(f'Sorted array: {elements}') 42 | 43 | -------------------------------------------------------------------------------- /Sorting/Homework/mergeSort.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector merge(vector &A, vector& B){ 4 | int sizeA=A.size(); 5 | int sizeB=B.size(); 6 | int i=0; 7 | int j=0; 8 | vector ans; 9 | 10 | //Compare and fill ans vector 11 | while (i mergeSort(vector& nums,int start, int end) { 38 | //Base Case 39 | if (start>end){ 40 | return {}; 41 | } 42 | if (start==end){ 43 | return {nums[start]}; 44 | } 45 | 46 | //Calculate Mid 47 | int mid= start+(end-start)/2; 48 | 49 | //MergeSortCall 50 | vector A = mergeSort(nums,start,mid); 51 | vector B = mergeSort(nums,mid+1,end); 52 | 53 | //MergeCall 54 | return merge(A,B); 55 | } 56 | 57 | vector sortArray(vector& nums) { 58 | int n=nums.size(); 59 | return mergeSort(nums,0,n-1); 60 | } 61 | }; -------------------------------------------------------------------------------- /Sorting/Homework/quickSort.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C 3 | 4 | #include 5 | 6 | /* Function to print an array */ 7 | void printArray(int arr[], int size) 8 | { 9 | int i; 10 | for (i=0; i < size; i++) 11 | printf("%d ", arr[i]); 12 | printf("\n"); 13 | } 14 | 15 | // } Driver Code Ends 16 | //User function Template for C 17 | void swap(int *nums,int i,int j){ 18 | int temp = nums[i]; 19 | nums[i]=nums[j]; 20 | nums[j]=temp; 21 | } 22 | //Function to sort an array using quick sort algorithm. 23 | void quickSort(int arr[], int start, int end) 24 | { 25 | // code here 26 | if (start