Apna Collage Final
Apna Collage Final
7. Space and time complexity (Third week 22/10/2020 - 28/10/2020) 15. Bit Manipulation (Fifth week 5/11/2020 - 11/11/2020)
- Definition and basics - Get, set, clear, update
- Polynomial evaluation - Is Power of 2
- Number of ones
8. Arrays (Third week) - Generate subsets
- Merge sort
16. Questions (Fifth week) - Quick sort
- Unique number in an array of duplicates
- 2 unique numbers in an array of duplicates 24. More sorting techniques (Sixth week)
- Unique number in an array of triplets - Counting sort
- DNF algorithm
17. Prime Sieve (Fifth week) - Wave sort
- Prime sieve
25. OOPS concepts (Sixth week)
18. Number Theory basics (Fifth week) - Classes and objects
- Euclid’s algo for GCD - Data members and functions
- Inclusion exclusion principle - Getters, setters
- Constructor & its types
19. Introduction to Recursion (Fifth week) - Shallow and deep copy
- Call stack - Copy assignment
- Fibonacci numbers - Destructor
- Factorial - Overloading
- Fast power
- First occurrence and last occurrence 26. STL (Sixth week)
- Increasing, Decreasing order - Pair class
- Time complexity for recursive functions (Master’s theorem) - Other STL functions, Iterators, comparators 3
- Templates
20. Recursion - ll (Fifth week)
- Tower of hanoi 27. Vectors (Sixth week)
- Reverse string - Intro
- Replace pi - Methods
- Remove duplicates - Sorting
- Move all x - Template
- Subsequence generation
- Generate permutations
28. Linked List (Sixth week)
21. Recursion - lll (Fifth week) - Introduction and implementation
- Permutation - Insertion in linked list
- Board game - Searching in linked list
- 0-1 Knapsack - Deletion in linked list
- Tiling problem - Reverse a linked list - Iterative and recursive solution
- Friends pairing problem - K reverse problem
- Count paths in Maze - Floyd's cycle detection and removal
- Doubly linked list
22. Backtracking (Sixth week 12/11/2020 - 18/11/2020) - Circular linked list
- Rat in maze problem
- N-queen problem
29. Challenges (Seventh week 19/11/2020 - 25/11/2020)
23. Divide and Conquer (Sixth week) - K append
- Even after odd - Different views of binary tree
- Intersection point - Nodes at distance K
- Merge 2 sorted linked lists - Lowest common ancestor
31. Infix, prefix, postfix (Seventh week) 37. Binary Search Tree (Ninth week 03/12/2020 - 09/12/2020)
- Infix, prefix, postfix expression evaluation - Introduction
- Infix to prefix using stack - Implementation and insertion
- Infix to postfix using stack - Searching
- Deletion
32. Queues (Seventh week) - Check for BST
- Introduction - Find min and max element
- Implement using array - Flatten a tree
- Implement using linked list - Construct from preorder
- Implement stack using queue - Catalan no concept
- Implement queue using stacks - Set STL
34. Questions (Eighth week 26/11/2020 - 02/12/2020) 39. Heaps (ninth week)
- Histogram area - Introduction to priority queue
- Circular tour - Heaps, insertion
- Balanced parentheses - Remove min and max element
- Build heap from array
35. Binary Trees (Eighth week) - Heapsort
- Introduction - Priority queue STL, Running median
- Preorder, inorder, postorder
- Level order 40. Challenges (ninth week)
- Sum at level K - Top k most frequent numbers in stream
- Height and Diameter of Binary Tree - Merge k sorted arrays
- BFS traversal - Length of Smallest Subsequence such that sum of elements is greater than equal
- DFS traversal to K
- Count and sum nodes
- Height balanced tree
41. Hashtable (Tenth week 10/12/2020 - 16/12/2020)
- Build balanced tree from array
- Introduction to hash functions
- Collision handling and separate chaining - Brackets all over
- Rehashing, load factor - Max length bitonic subsequence
- Unordered Map STL - Max sum submatrix
- Max frequency character (https://www.geeksforgeeks.org/maximum-sum-rectangle-in-a-2d-matrix-dp-27/)
- Vertical order print
47. Graphs - l (Twelfth week 24/12/2020 - 30/12/2020)
42. Hashing Problems (Tenth week) - Introduction
- Number of subarrays with sum 0 - Representation
- Longest subarray with sum k - Adjacency list implementation
- Longest consecutive subsequence - BFS
(https://www.geeksforgeeks.org/longest-consecutive-subsequence/) - DFS
- Minimum window substring - Topological sort
- Cycle detection in directed and undirected graph
43. Greedy Algorithm (Tenth week) - Connected components
- Introduction - Pairing problem
- Activity selection problem - Bipartite graph check
- Job selection problem
- 0/n knapsack problem 48. Graphs - ll (Twelfth week)
- Optimal merge pattern problem - Disjoint set introduction
- Huffman coding problem - Union and find
- Path compression
44. Challenges (Tenth week) - Union by rank optimisation
- Coin change - Implementation
- Max Circles
- Dividing array 49. Graphs - lll (Twelfth week)
- Kruskal’s algorithm
45. Dynamic Programming (Eleventh week 17/12/2020 - 23/12/2020) - Prim’s algorithm
- Introduction - Dijkstra’s algorithm
- Fibonacci problem - Bellman ford algorithm
- Minimum steps to 1 - Floyd Warshall algorithm
- Minimum coin change - Strongly connected component using Kosaraju’s algo
- Maximum subarray sum
- Snakes and Ladders 50. Challenges (Twelfth week)
- 0/1 knapsack - Snakes and ladders problem
- LIS and LCS problem - MST problem
- Matrix chain multiplication - Beautiful vertices
- Friends pairing problem 51. Questions (Thirteenth week 31/12/2020 - 6/01/2021)
- Catalan number concept - Sum of all submatrices in a matrix
- Optimal game strategy - Searching in sorted matrix
- Optimal binary search tree - Rain water harvesting (https://www.geeksforgeeks.org/trapping-rain-water/)
- All pair shortest path problem
52. Number theory Advanced (Thirteenth week)
46. Challenges (Eleventh week) - Extended Euclid
- No. of Binary String - Multiplicative modulo inverse
- LCS w 3 strings - Euler totient function
- Wildcard pattern matching - Segmented sieve
- Binary/Modular exponentiation - both recursive and iterative
- Matrix Exponentiation - It’s cases
- Fermat little theorem, wilson theorem
53. Tries (Thirteenth week)
- Data structure introduction
- Insertion
- Searching
- Phonebook problem
- Xor subarray problem
A program is a set of instructions that tells a computer what to do in order to come up with A high-level language cannot be understood directly by a computer, and it needs to be
a solution to a particular problem. Programs are written using a programming language. translated into machine code. There are two ways to do this, and they are related to how
A programming language is a formal language designed to communicate instructions to a the program is executed: a high-level language can be compiled or interpreted.
computer. There are two major types of programming languages: low-level languages and
high-level languages. Compiler vs Interpreter
A compiler is a computer program that translates a program written in a high-level language
Low-Level Languages to the machine language of a computer.
Low-level languages are referred to as 'low' because they are very close to how different
hardware elements of a computer actually communicate with each other. Low-level The high-level program is referred to as 'the source code.' The compiler is used to translate
languages are machine oriented and require extensive knowledge of computer hardware source code into machine code or compiled code. This does not yet use any of the input
and its configuration. There are two categories of low-level languages: machine language data. When the compiled code is executed, referred to as 'running the program,' the
and assembly language. program processes the input data to produce the desired output.
Machine language, or machine code, is the only language that is directly understood by the An interpreter is a computer program that directly executes instructions written in
computer, and it does not need to be translated. All instructions use binary notation and are a programming language, without requiring them previously to have been compiled into
written as a string of 1s and 0s. A program instruction in machine language may look a machine language program.
something like this:
However, binary notation is very difficult for humans to understand. This is where assembly C++ is a cross-platform language that can be used to create high-performance applications.
languages come in. It was developed by Bjarne Stroustrup, as an extension to the C language. The language was
updated 3 major times in 2011, 2014, and 2017 to C++11, C++14, and C++17.
An assembly language is the first step to improve programming structure and make
machine language more readable by humans. An assembly language consists of a set of Why Use C++?
symbols and letters. A translator is required to translate the assembly language to machine
language called the 'assembler.' 1. C++ is one of the world's most popular programming languages.
While easier than machine code, assembly languages are still pretty difficult to understand.
This is why high-level languages have been developed. 2. C++ can be found in today's operating systems, Graphical User Interfaces, and
embedded systems.
High-Level Languages
3. C++ is an object-oriented programming language which gives a clear structure to
A high-level language is a programming language that uses English and mathematical programs and allows code to be reused, lowering development costs.
symbols, like +, -, % and many others, in its instructions. When using the term 'programming
languages,' most people are actually referring to high-level languages. High-level languages 4. C++ is portable and can be used to develop applications that can be adapted to
are the languages most often used by programmers to write programs. Examples of high- multiple platforms.
level languages are C++, Fortran, Java and Python.
5. C++ is fun and easy to learn!
Learning a high-level language is not unlike learning another human language - you need to
learn vocabulary and grammar so you can make sentences. To learn a programming
6. As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or
language, you need to learn commands, syntax and logic, which correspond closely to
vice versa.
vocabulary and grammar.
The code of most high-level languages is portable and the same code can run on different
hardware without modification. Both machine code and assembly languages are hardware
How to start writing programs? Pseudocode
Flowcharts
Flowcharts are written with program flow from the top of a page to the bottom. Each
command is placed in a box of the appropriate shape, and arrows are used to direct
program flow. The following shapes are often used in flowcharts:
Pseudocode
1. Start
2. Input 2 numbers number1 and number2
3. Add number1 and number2 to find sum
4. Print sum
5. End
Ques2. Write a flowchart and pseudocode to find the area of a square. Ques3. Write a flowchart and pseudocode to find simple interest.
Pseudocode
1. Start
Pseudocode
2. Input length of the square
3. Calculate area of square as length * length
1. Start
4. Print area 2. Input a principal as P, rate as R, and time as T
5. End
3. Calculate simple interest as P * R * T
4. Print simple interest
5. End
Ques4. Write a flowchart and pseudocode to convert temperature from Ques5. Write a flowchart and pseudocode to check if a number is odd or even.
Fahrenheit (℉) to Celsius (℃).
Pseudocode
Pseudocode 1. Start
2. Input a number
1. Start 3. If remainder when number is divided is 0, print Even number
2. Read temperature in Fahrenheit 4. Else print Even number
3. Calculate temperature with formula C=5/9*(F-32) 5. End
4. Print C
5. End
Ques6. Write a flowchart and pseudocode to find the max of 3 numbers. Ques7. Write a flowchart and pseudocode to find the sum of n natural
numbers.
Pseudocode
1. Start
2. Read three numbers a,b and c
Pseudocode
3. Compare a and b, if a > b
Compare a and c, if a > c
1. Start
Print a
2. Read a number n
Else
3. Repeat the following till n becomes equal to 0
Print c
Add n in sum
Else
Decrement n
Compare b and c, if b > c
4. Print sum
Print b
5. End
Else
Print c
4. End
Ques8. Write a flowchart and pseudocode to find the factorial of a number. Ques9. Write a flowchart and pseudocode to find if a number is prime or not.
Pseudocode
1. Start
Pseudocode 2. Read a number n
3. Initialise divisor = 2
1. Start 4. Repeat till divisor < n
2. Read a number n If n is divisible by divisor
3. Initialise m =1 Print Non-Prime
4. Repeat the following till m becomes equal to n End
Multiply m with factorial Else
Increment m divisor = divisor + 1
5. Print factorial 5. Print Prime
6. End 6. End
Ques10. Write a flowchart and pseudocode to print all prime numbers till n. Brain Teasers
1. You are standing outside of a room with no windows. The room has three
light bulbs and three switches outside of the room. Each switch controls
one of the light bulbs. You may only enter the room one time. How can
you find out what switch goes to each light bulb?
(asked in LinkedIn)
Pseudocode Solution
To find out what switch goes to what light bulb, you could turn on the
1. Start
2. Read a number n first switch and wait five minutes.
3. Initialise num = 2
4. While num <= n do After five minutes have passed, turn off the first switch and turn on the
second switch.
Initialise div = 2
While div < num do
If n is divisible by div Look for the warm light bulb when you walk back into the room.
num = num + 1
Else The light that is on goes to the second switch, the warm light bulb goes to
div = div + 1 the first switch and the last light bulb goes to the third switch.
print num
num = num + 1
5. End
2. You have a 3 gallon jug and 5 gallon jug, how do you measure out 3. You re about to get on a plane to Seattle. You want to know if it s raining.
exactly 4 gallons? You call 3 random friends who live there and ask each if it s raining. Each
(asked in Google) friend has a 2/3 chance of telling you the truth and a 1/3 chance of
messing with you by lying. All 3 friends tell you that Yes it is raining.
What is the probability that it s actually raining in Seattle?
(asked in Facebook)
Solution
First fill the 3 gallon jug. Then pour the 3 gallons into the 5 gallon jug.
Solution
Now the 3 gallon jug is empty, and the 5 gallon jug has 3 gallons in it.
You only need 1 of your friends to be telling the truth for it to be raining in
Seattle.
Fill the 3 gallon jug again and pour into the 5 gallon jug. Only 2 gallons will fit
because it already has 3. Exactly 1 gallon is left in the 3 gallon jug.
It s fastest just to calculate the odds that all are lying, and it s not raining.
Dump out the 5 gallon jug.
Each friend has a chance of lying. Multiply the odds together… you get 1/27
(1/3 * 1/3 * 1/3).
Pour your 1 gallon into the 5 gallon jug. Fill up the 3 gallon jug one more time
and pour it into the 5 gallon jug. You have exactly 4 gallons!
So 1/27 is the probability that all 3 friends lied at the same time.
The probability that at least 1 told you the truth? 26/27 or around a 96% that
it s raining in Seattle.
Variables 1. int
This data type is used to store integers.
A variable is a container (storage area) used to hold data. It occupies 4 bytes in memory.
Each variable should be given a unique name (identifier). It can store values from -2147483648 to 2147483647.
Eg. int age = 18
int a=2;
2. float and double
Here a is the variable name that holds the integer value 2.
Used to store floating-point numbers (decimals and exponentials)
The value of a can be changed, hence the name variable.
Size of float is 4 bytes and size of double is 8 bytes.
Float is used to store upto 7 decimal digits whereas double is used
There are certain rules for naming a variable in C++
to store upto 15 decimal digits.
1. Can only have alphabets, numbers and underscore.
Eg. float pi = 3.14
2. Cannot begin with a number.
double distance = 24E8 // 24 x 108
3. Cannot begin with an uppercase character.
4. Cannot be a keyword defined in C++ language (like int is a keyword).
3. char
This data type is used to store characters.
Fundamental Data Types in C++
It occupies 1 byte in memory.
Characters in C++ are enclosed inside single quotes .
Data types are declarations for variables. This determines the type and size of
ASCII code is used to store characters in memory.
data associated with variables which is essential to know since different data
Eg char ch a
types occupy different size of memory.
int Integer 4
float Floating-point 4
char Character 1
4. bool
bool Boolean 1
This data type has only 2 values true and false.
It occupies 1 byte in memory.
void Empty 0
True is represented as 1 and false as 0.
Eg. bool flag = false
C++ Type Modifiers
Type modifiers are used to modify the fundamental data types.
long long int 8 used for very large integers (equivalent to long
long int).
unsigned long 8 used for very large positive integers or 0
long (equivalent to unsigned long long int)
We will be studying the derived and user-defined data types in detail in the
further video lectures.
6. cout ”Hello World!\n”;
Hello World Program This is a C++ statement. cout represents the standard output stream in
C++. It is declared in the iostream standard file within the std namespace.
// Hello world program in C++ The text between quotations will be printed on the screen.
\n will not be printed, it is used to add line break.
#include<iostream> Each statement in C++ ends with a semicolon (;)
using namespace std;
7. return 0;
int main() return signifies the end of a function. Here the function is main, so when
{ we hit return 0, it exits the program. We are returning 0 because we
mentioned the return type of main function as integer (int main). A zero
cout << "Hello World!\n";
indicates that everything went fine and a one indicates that something
return 0;
has gone wrong.
}
The << operator can be used multiple times in a single statement. Take a look It is possible to use the endl manipulator instead of the new-line character.
at an example:
#include<iostream>
cout << "This is one sentence." << endl;
using namespace std;
cout << "This is another." << endl;
int main()
{
Standard input (cin)
cout << "Hello, " << "this is a test " << "string.";
In most cases the standard input device is the keyboard. With the cin and >>
return 0;
operators it is possible to read input from the keyboard.
}
Take a look at an example:
It is possible to combine variables and text:
#include<iostream>
#include<iostream>
using namespace std;
using namespace std;
int main()
int main()
{
{
char ch;
char Yes = 'y';
cout << "Press a character and press return: ";
cout << "Print the character " << Yes;
cin >> ch;
return 0;
cout << ch;
}
return 0;
}
Note: The input is processed by cin after the return key is pressed.
The cin operator will always return the variable type that you use with cin. So
if you request an integer you will get an integer and so on. This can cause an
error when the user of the program does not return the type that you are
expecting. (Example: you ask for an integer and you get a string of characters.)
In this case the user must give two input values, that are separated by any
valid blank separator (tab, space or new-line).
}
Decision making
return 0 ;
if/else }
The if block is used to specify the code to be executed if the condition specified
in if is true, the else block is executed otherwise.
nested if
#include <iostream> To specify conditions within conditions we make the use of nested ifs.
using namespace std ;
int main () {
int x,y ;
cin >> x >> y ;
if ( x == y ) {
cout << "Both the numbers are equal" ;
}
else if ( x > y ) {
cout << "X is greater than Y" ;
}
else {
cout << "Y is greater than X" ;
cin>>n1>>n2;
Problems
int max, min;
1. Program to check if a number is even or odd.
#include<iostream> if(n1>n2){
int main(){ }
else{
int n; max=n2;
cin>>n; min=n1;
}
if(n%2==0){
cout<<"Even"<<endl; cout<<"Max= "<<max<<endl;
} cout<<"Min= "<<min<<endl;
else{
cout<<"Odd"<<endl; return 0;
} }
3. Program to find the maximum among three numbers.
return 0;
} #include<iostream>
using namespace std;
2. Program to find maximum, minimum among two numbers.
int a,b,c;
int main(){ cin>>a>>b>>c;
}
else{ if (sidea == sideb && sideb == sidec)
cout<<c<<endl; {
return 0;
return 0;
}
}
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
int main()
int main()
{
{
char c;
int isLowercaseVowel, isUppercaseVowel;
int sidea, sideb, sidec;
cout << "Enter an alphabet: ";
cin >> c;
if (isLowercaseVowel || isUppercaseVowel)
cout << c << " is a vowel.";
else
cout << c << " is a consonant.";
return 0;
}
Loops in C++ The for loop is initialized by the value 1, the test condition is i<=5 i.e the loop is
executed till the value of i remains lesser than or equal to 5. In each iteration
the value of i is incremented by one by doing i++.
A loop is used for executing a block of statements repeatedly until a particular
condition is satisfied. A loop consists of an initialization statement, a test
condition and an increment statement.
#include<iostream> #include<iostream>
cout<<i<<" ";
} while(i<=5){
cout<<i<<" ";
return 0; i++;
} }
return 0;
Output – }
Output-
Output-
The while loop is initialized by the value 1, the test condition is i<=5 i.e the loop
is executed till the value of i remains lesser than or equal to 5. In each iteration
the value of i is incremented by one by doing i++.
The do while loop variable is initialized by the value 1, in each iteration the
value of i is incremented by one by doing i++, the test condition is i<=5 i.e the
loop is executed till the value of i remains lesser than or equal to 5. Since the
do hile loop
testing condition is checked only once the loop has already run so a do while
The syntax for while loop is loop runs at least once.
do { Examples
// body of loop;
Ques1. Program to find sum of natural numbers till n.
}
while (condition);
#include<iostream>
using namespace std;
#include<iostream>
using namespace std; int main(){
int sum=0;
do for(int counter=1;counter<=n;counter++){
{ sum=sum+counter;
cout<<i<<" "; }
i++;
} while (i<=5); cout<<sum<<endl;
return 0; return 0;
} }
Ques2. Program to display multiplication table upto 10. while (number >= 0) {
#include <iostream>
sum += number;
using namespace std;
cout << "Enter a number: ";
cin >> number;
int main()
}
{
int n;
cout << "\nThe sum is " << sum << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
Jumps in loops are used to control the flow of loops. There are two statements #include <iostream>
used to implement jump in loops - Continue and Break. These statements are using namespace std;
used when we need to change the flow of the loop when some specified
int main() {
condition is met.
int n;
1. Continue cout<<"Enter a number: ";
cin>>n;
Continue statement is used to skip to the next iteration of that loop. This
means that it stops one iteration of the loop. All the statements present for (int i=1; i<=n; i++) {
after the continue statement in that loop are not executed. if (i%2==0) { // i is even
continue;
int i; }
for (i=1; i<=20; i++) { cout<<i<<endl;
}
if (i%3==0) {
continue; return 0;
} }
cout<<i<<endl;
}
Ques2. Write a program to check if a given number is prime or not.
In this for loop, whenever i is a number divisible by 3, it will not be printed #include <iostream>
as the loop will skip to the next iteration due to the continue statement. using namespace std;
Hence, all the numbers except those which are divisible by 3 will be printed.
int main() {
2. Break int n;
cout<<"Enter a number: "
Break statement is used to terminate the current loop. As soon as the break cin>>n;
statement is encountered in a loop, all further iterations of the loop are
stopped and control is shifted to the first statement after the end of loop. int i;
for (i=2; i<n; i++) {
int i; if (n%i==0) { //found a factor
for (i=1; i<=20; i++) { of n
cout<<"Not a prime"<<endl;
if (i==11) { break;
break; }
} }
cout<<i<<endl; if (i==n) { //loop has
} completed all iterations
cout<<"Prime Number"<<endl;
In this loop, when i becomes equal to 11, the for loop terminates due to }
break statement, Hence, the program will print numbers from 1 to 10 return 0;
only. }
Ques3. Write a program to print all prime numbers in a given range
#include <iostream>
using namespace std;
int main() {
int a,b;
cout<<"Enter 2 numbers: ";
cin>>a>>b;
return 0;
}
Switch Statement
Switch case statements are a substitute for long if statements that compare a Examples
variable to multiple values. After a match is found, it executes the
corresponding code of that value case. Ques1. Write a program to write a simple calculator.
Syntax:
#include <iostream>
using namespace std;
case '+':
cout<<n1+n2<<endl;
The variable in switch should have a constant value. break;
The break statement is optional. It terminates the switch case '-':
cout<<n1-n2<<endl;
statement and moves control to the next line after switch. break;
If break statement is not added, switch will not get terminated and case '*':
cout<<n1*n2<<endl;
it will continue onto the next line after switch.
break;
Every case value should be unique. case '/':
cout<<n1/n2<<endl;
Default case is optional. But it is important as it is executed when
break;
no case value could be matched. case '%':
cout<<n1%n2<<endl;
break;
default:
cout<<"Operator not found!"<<endl;
break;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
char c;
switch (c)
{
case 'a':
cout<<"It is a vowel"<<endl;
break;
case 'e':
cout<<"It is a vowel"<<endl;
break;
case 'i':
cout<<"It is a vowel"<<endl;
break;
case 'o':
cout<<"It is a vowel"<<endl;
break;
case 'u':
cout<<"It is a vowel"<<endl;
break;
default:
cout<<"It is a consonant"<<endl;
break;
}
return 0;
}
Operators in C++ Example -
Operators are nothing but symbols that tell the compiler to perform some int a=10;
specific operations. Operators are of the following types - int b;
b = a++;
cout<<a<<" "<<b<<endl;
1. Arithmetic Operators
Arithmetic operators perform some arithmetic operation on one or two Output : 11 10
operands. Operators that operate on one operand are called unary
arithmetic operators and operators that operate on two operands are int a=10;
int b;
called binary arithmetic operators.
+,-,*,/,% are binary operators. b = ++a;
++, -- are unary operators. cout<<a<<" "<<b<<endl;
> Gives true if left operand is more than right A>B is not
Pre-incrementer : It increments the value of the operand instantly. operand true
Post-incrementer : It stores the current value of the operand temporarily
and only after that statement is completed, the value of the operand is < Gives true if left operand is less than right operand A<B is true
incremented.
>= Gives true if left operand is more than right A>=B is not
Pre-decrementer : It decrements the value of the operand instantly.
operand or equal to it true
Post-decrementer : It stores the current value of the operand temporarily
and only after that statement is completed, the value of the operand is <= Gives true if left operand is more than right A<=B is true
decremented. operand or equal to it
If we need to check whether a number is divisible by both 2 and 3, we will
Example - use AND operator
We need to write a program which prints if a number is more than 10, (num%2==0) && num(num%3==0)
equal to 10 or less than 10. This could be done using relational operators
with if else statements. If this expression gives true value then that means that num is divisible by
both 2 and 3.
int n;
cin>>n; (num%2==0) || (num%3==0)
if(n<10){ If this expression gives true value then that means that num is divisible by
cout<<"Less than 10"<<endl; 2 or 3 or both.
}
else if(n==10){
cout<<"Equal to 10"<<endl;
} 4. Bitwise Operators
else{
cout<<"More than 10"<<endl;
Bitwise operators are the operators that operate on bits and perform bit-
} by-bit operations.
3. Logical Operators
Operator Operation Example
Logical operators are used to connect multiple expressions or conditions
together. & Binary AND. Copies a bit to the result if it exists in 0101
We have 3 basic logical operators. both operands. & 0110
0100
Suppose : A=0 and B=1
| Binary OR. Copies a bit if it exists in either operand. 0101
| 0110
Operator Operation Example 0111
&& AND operator. Gives true if both operands are non- (A && B) is ^ Binary XOR. Copies the bit if it is set in one operand 0101
zero false but not both. ^ 0110
0011
|| OR operator. Gives true if atleast one of the two (A || B) is
operands are non-zero. true ~ Binary Ones Complement. Flips the bit. ~0101 =>
! NOT operator. Reverse the logical state of operand !A is true 1010
5. Assignment Operators
Precedence of Operators
Operator Operation Example
Category Operator Associativity
= Assigns value of right operand to left operand A=B will put value
of B in A Postfix () [] -> . ++ - - Left to right
+= Adds right operand to the left operand and A+=B means A = Unary + - ! ~ ++ - - (type)* & sizeof Right to left
assigns the result to left operand. A+B
Multiplicative */% Left to right
-= Subtracts right operand from the left operand A-=B means A=A-B
and assigns the result to left operand. Additive +- Left to right
*= Multiplies right operand with the left operand A*=B means A=A*B
Shift << >> Left to right
and assigns the result to left operand.
/= Divides left operand with the right operand and A/=B means A=A/B Relational < <= > >= Left to right
assigns the result to left operand.
Equality == != Left to right
sizeof() Returns the size of variable If a is integer Logical AND && Left to right
then sizeof(a) will
return 4 Logical OR || Left to right
Conditional ?: Right to left }
3.
Examples
#include<stdio.h>
Ques. Give the output of the following programs. int main()
1. {
#include<stdio.h> int x = 2;
{ return 0;
int a = 5; }
a = 1, 2, 3; Ans. False
printf("%d", a); (As & is a unary operator we have to assume all decimal values to
binary(0's and 1's)
return 0; 210 = 00000010 2
} Now we go for condition (00000010 & 00000001)
Clearly, condition false as it leads to 0 when multiplied.)
Ans. 1
(Priority for the values assigned to any variable is given from left to 4.
right) #include<stdio.h>
2. int main()
#include<stdio.h> {
{ }
int a; Ans. 6
a = (1, 2, 3); (2-- stands meaningless)
printf("%d", a); 5.
return 0; #include<stdio.h>
int main()
{
int i = 10;
i++;
i * i;
printf("%d\n",i);
return 0;
}
Ans. 11
(i++ alone store the result in variable i.)
6.
#include<stdio.h>
int main()
{
int a = 1, b = 3, c;
c = b << a;
b = c * (b * (++a)--);
a = a >> b;
printf("%d",b);
return 0;
}
Ans. 36
(c = 0011 << 1
c = 0110
b = 6* (3*(2)--)
b = 6*6
)
Nested Loops Print a hollow rectangle
Loops within loops are termed as nested loops.
Pattern Problems
The easiest way to understand the working of a nested loop is by solving pattern printing
problems.
#i c de <i ea >
Print a solid rectangle
i g a e ace d;
i ai ()
i , c ;
c << "E e he be f :\ ";
ci >> ;
c << "E e he be f c :\ ";
ci >> c ;
f (i i = 1
; i <= i++)
;
f (i = 1; j <= c
j ; j++)
c < "*";
<
c << e d ;
e 0;
f (i i = ; i >= 1; i--)
Print Half Pyramid Pattern using Stars f (i = 1; j <= i; j++)
j
c < "* ";
<
c << e d ;
e 0;
#i c de <i ea >
Print Half Pyramid after 180 degree rotation
i g a e ace d;
i ai ()
i ;
ci >> ;
f (i i = 1
; i <= ;
i++)
f (i = 1; j <
j = i; j++)
c < "*";
<
#i c de <i ea >
c << e d ;
i g a e ace d;
e 0;
i ai ()
i ;
ci >> ;
Print an Inverted Half pyramid
f (i i = 1; i <= ; i++)
f (i j = 1; j <= ; j++)
if ( j <= - i)
c << " ";
e e
c << "*";
c << e d ;
#i c de <i ea >
e 0;
i g a e ace d;
i ai ()
i ;
ci >> ;
Print Half Pyramid using numbers Print Inverted Half Pyramid using numbers
#i c de <i ea >
#i c de <i ea >
i g a e ace d;
i g a e ace d;
i ai ()
i ai ()
i ;
i ;
ci >> ;
ci >> ;
c << e d ;
c << "\ ";
e 0;
e 0;
#i c de <i ea >
i g a e ace d;
i ai ()
i ;
ci >> ;
f (i i = 1
; i <= ; i++) Print Floyd's Triangle
f i
( = 1; j <= i; ++j)
j
c < i << " ";
<
c << e d ;
e 0;
i g a e ace d;
i ai ()
i ;
ci >> ;
i be = 1;
f (i i = 1; i <= ; i++)
f (i j = 1; j < = i; j++)
#i c de <i ea > c << be < < " ";
be ++;
i g a e ace d;
c << e d ;
i ai ()
i ; e 0;
ci >> ;
f (i = 1
i ; i <= ; i++)
f (i = 1; j <= - i + 1; ++j)
j
c < i << " ";
<
c << e d ;
Print 0-1 pattern
e 0;
#i c de<i ea >
using namespace d; int i,j,r;
int ai ()
cin>>r;
int i,j, ;
for(i=1;i<=r;i++)
ci >> ; {
int k=i;
for(i=1;i<= ;i++) for(j=1;j<=(r-i);j++)
{
for(j=1;j<=i;j++)
cout<<" ";
if((i+j)%2==0)
c <<" 1"; for( ;j<=r;j++)
else {
c <<" 0"; cout<<k<<" ";
k--;
c <<e d ;
k=1;
for( ;j<(r+i);j++)
return 0;
{
k++;
cout<<k<<" ";
Pattern - 5 Palindromic pattern
for( ;j<=(2*r-1);j++)
{
cout<<" ";
cout<<endl;
#include<iostream>
using namespace std;
c << e d ;
ace--;
ace = 0
;
f (i = ; i >= 1; i--)
i
f (i = 1; j <= ace; j++)
j
e 0;
#i c de <i ea >
i g a e ace d;
i ai ()
i ;
ci >> ;
c << e d ;
ace--;
#i c de <i ea >
ace = 0
;
f (i = ; i >= 1; i--)
i i g a e ace d;
f (i = 1; j <= ace; j++)
j
c < " ";
< i ai ()
i ;
f (i j = 1; j <= 2 * i - 1 ; j++) ci >> ;
if (j == 1 j == 2 * i - 1)
c << " *"; i ace = (2 * - 1) / 2;
e e f (i i = 1; i <= ; i++)
c << " "; f (i j = 1; j <= ace; j++)
c << "*";
c << e d ;
ace--;
c << "*";
ace = 0
;
f (i = ; i >= 1; i--)
i c << "\ ";
f (i = 1; j <= ace; j++)
j
c < "*";
< e 0;
c << e d ;
ace++;
#i c de <i ea >
e 0;
i g a e ace d;
i ai ()
i ;
Print Solid Rhombus ci >> ;
f (i i = 1
; i <= ;
i++)
f (i = 1; j <
j = - i; j++)
c < " ";
<
i ai ()
i ;
ci >> ;
c << "\ ";
f (i = 1
i ; i <= ;
i++)
e 0;
f (i = 1; j <
j = - i; j++)
c < " ";
<
#i c de <i ea >
e 0;
f (i j = 1; j <= e _ ace; j++)
Print Sold Butterfly Pattern c << " ";
e 0;
#i c de <i ea >
i g a e ace d;
i ai ()
i ;
ci >> ;
f (i i =
1; i <= ; i++)
f (i =
i ; i >= 1; i--) i e _ ace = 2 * - 2 * i;
i e _ ace = 2 * - 2 * i; f (i j = 1; j <= i; j++)
f (i j = 1; j <= i; j++) if ( j == 1 j == i)
c << "*"; c << "*";
e e
c << " ";
Print Pascal s Triangle
f (i j = 1; j <= e _ ace; j++)
c << " ";
i g a e ace d;
f (i i = ; i >= 1; i--)
i e _ ace = 2 * - 2 * i; i ai ()
f (i j = 1; j <= i; j++) i ;
if ( j == 1 j == i) ci >> ;
c << "*";
e e i c ef = 1 ;
c << " "; f (i i = 0; i < ; i++)
f (i ace = 1; ace <= - i; ace++)
c << " ";
f (i j = 1; j <= e _ ace; j++)
c << " "; f (i j = 0; j < = i; j++)
if (j == 0 == 0)
i
f (i j = 1; j <= i; j++) c ef = 1;
if (j == 1 j == i) e e
c << " *"; c ef = c ef * (i - j + 1) / j;
e e
c << " "; c << c ef << " ";
c << e d ;
c << "\ ";
e 0;
e 0;
Zig-Zag Pattern
#include<iostream>
using namespace std;
int main(){
int i,j,n;
cin>>n;
for(i=1;i<=3;i++){
for(j=1;j<=n;j++){
if(((i+j)%4==0)||((i==2)&&(j%4==0)))
cout<<"* ";
else
cout<<" ";
cout<<endl;
return 0;
1*23 + 1*22 + 0*21 + 1*20 = 1*8 + 1*4 + 0*2 + 1*1 = 13
D N F 13
1101 .
D .
10 .
I .N
0-9. E . 678.
.
B N C N D B
C 0 1 . :
2 . 0 1 1. 2 .
. E . 10011. 2. D 2
3. .
4. .
C
1 5 2
C B D
4 3 2 1
<= 10000 (10 ) 1000 (10 ) 100 (10 ) 10 (10 ) 1 (100)
1. 10001 (A = 17)
2. 11000001 (A = 193)
A , 152. 3. 111111111 (A = 511)
152
152 = 1*100 + 5*10 + 2*1
152 = 1*102 + 5*101 + 2*100 C D B
1. 247 (A = 11110111)
10( ) 1 2. 148 (A = 10010100)
. 3. 18 (A = 10010)
C N B D
A , 1101 N
.
2 . 1 .E .
2,3,5,7,19 .
1 1 0 1
<= 4
16 (2 ) 3
8 (2 ) 2
4 (2 ) 1
2 (2 ) 1 (20) A N
A
. E. 153 = 13 + 53 + 33 = 1 + 125 + 27 = 153.
if ( < = 1
)
f ag = fa e;
F
F if (f ag)
. c << " P i e\ ";
L , e e
c << " N P i e\ ";
, , + , +2 , 2 +3 , 3 +5 .
e 0;
L 0 1.
0, 1, 1, 2, 3, 5, 8, 13 .
F
F #i c de <i ea >
.
i g a e ace d;
F !. i ai ()
i ;
E. 4! = 4 * 3 * 2 * 1 = 24. ci >> ;
hi e ( > 0)
i e = % 10;
c < e <
< < "\ ";
= / 10;
C
e 0;
#i c de <i ea >
i g a e ace d;
i ai () C A
i ;
#i c de <i ea >
ci >> ;
i g a e ace d;
b f ag = e;
f (i i = 2; i * i <= ; i++)
i ai ()
if ( % i == 0)
i ;
f ag = fa e;
ci >> ;
b ea ;
i 0, g_
= = ;
hi e ( > 0)
i e = % 1
0;
= + e * e * e ; e e
= / 10; i c _f, a = 0, b = 1, i = 3;
c < a << " " << b << " ";
<
hi e ( i <= )
if ( g_ =
= ) c _f = a + b;
c < "
< A g N be \ "; c << c _f << " ";
e e a = b;
c < "
< N A g N be \ "; b = c _f;
i++;
e 0;
C
#i c de <i ea > N
i g a e ace d; E. G 1879 9781.
100020 20001 (N : ).
i ai ()
i ; #i c de <i ea >
ci >> ;
i g a e ace d;
i fac = 1;
f (i = 1; i
i <= ; i++) i ai ()
fac = f ac * i ; i ;
ci >> ;
i ai () e 0;
i ;
ci >> ;
if(flag==0){
cout<<"prime"<<endl; return 0;
} }
return 0;
} Ques4. Write a program to check if a number is Armstrong number
#include <iostream>
Ques2. Write a program to print all the digits of a positive decimal #include<math.h>
number from right to left using namespace std;
int main() {
int n;
cin>>n;
int sum=0;
int originaln=n;
while(n>0){
int lastdigit= n%10;
sum+= pow(lastdigit,3);
n=n/10;
}
if(sum==originaln){
cout<<"Armstrong number"<<endl;
}
else{
cout<<"not armstrong"<<endl;
}
return 0;
}
Ques5. Write a program to print the ASCII value of any given character.
Ques6. Write a program to display all factors of a number.
Ques7. Write a program to find the factorial of a given number.
Ques8. Write a program to find whether a given character is a vowel or a
consonant.
Functions Main function
The main function is a special function as the computer starts running the code
from the beginning of the main function. Main function serves as the entry
A function is a block of code that performs a specific task. point for the program.
return-type function_name (parameter 1, parameter …… parameter n){ int sum = num1 + num2;
//function_body return sum;
}
}
return-type
The return type of a function is the data type of the variable that that function int main()
returns.
For eg. if we write a function that adds 2 integers and returns their sum then {
the return type of this function will be ‘int’ as we will returning sum that is an int a,b;
integer value.
cin>>a>>b;
When a function does not return any value, in that case the return type of the
function is ‘void’.
cout<<add(a,b)<<endl;
function_name
It is the unique name of that function.
It is always recommended to declare a function before it is used. return 0;
}
Parameters
A function can take some parameters as inputs. These parameters are specified Ques2. Write a program to print a given number using functions.
along with their data types.
For eg. if we are writing a function to add 2 integers, the parameters would be
#include <iostream>
passed like –
using namespace std;
int add (int num1, int num2)
void display(int a){
cout<<a<<endl;
return;
}
int main()
{
int a;
cin>>a;
print(a);
return 0;
}
Coding questions on functions
Ques2. Write a program to print Fibonacci sequence.
Ques1. Write a program to print all prime numbers between 2 given numbers.
#include<iostream>
#include<iostream> using namespace std;
#include<math.h>
using namespace std; void fib(int n){
int main(){
for(int i=a;i<=b;i++){
if(isPrime(i)){ int n;
cout<<i<<endl; cin>>n;
}
} fib(n);
return 0; return 0;
} }
int fact(int n){
Ques3. Write a program to find the factorial of a given number.
int factorial=1;
for(int i=2;i<=n;i++){
#include<iostream> factorial*=i;
int factorial=1;
for(int i=2;i<=n;i++){ int main(){
factorial*=i;
} int n,r;
}
int ans = fact(n)/(fact(r)*fact(n-r));
int n;
cin>>n; return 0;
}
#include<iostream>
Ques4. Write a program to find the binary coefficient (nCr)
using namespace std;
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
cout<<fact(i)/(fact(j)*fact(i-j))<<" ";
}
cout<<endl;
}
return 0;
}
Practice questions
Ques6. Write a program to find out whether a given number is even or odd
using functions.
Ques8. Write a program with two functions to print the maximum and the
minimum number respectively among three numbers entered by user.
Practice (Functions) Conversions
Decimal to octal
Decimal to hexadecimal Add two binary numbers
Codes
d) Decimal to binary
b) Octal to decimal
4. Add two binary numbers
e) Decimal to octal
f) Decimal to hexadecimal
Space and Time Complexity
Time Complexity
Time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the input.
Types of notations
1. O-notation: It is used to denote asymptotic upper bound. For a given function g(n), we denote it by O(g(n)). Pronounced as “big-oh of g of
n”. It also known as worst case time complexity as it denotes the upper bound in which algorithm terminates.
2. Ω-notation: It is used to denote asymptotic lower bound. For a given function g(n), we denote it by Ω(g(n)). Pronounced as “big-omega of
g of n”. It also known as best case time complexity as it denotes the lower bound in which algorithm terminates.
3. 𝚯-notation: It is used to denote the average time of a program. Time complexity: O(n*m)
Examples:
Space Complexity
Space complexity of an algorithm quantifies the amount of time taken by a program to run as a function of length of the input. It is directly
proportional to the largest memory your program acquires at any instance during run time.
For example: int consumes 4 bytes of memory.
Ge ing a ed i h A a
Finding Max and Min element
Step Taking the input n and declaring an Integer Array of si e n
Step Iterating the Array and calculating the maximum and minimum
elements
P ac ice e ion
Running sum of an Array
Kids with the greatest number of candies
Sorting (8.3) 3. Insertion Sort:
Idea: Take an element from the unsorted array, place it in its corresponding
1. Selection Sort: position in the sorted part, and shift the elements accordingly.
Idea: The inner loop selects the minimum element in the unsorted array Time Complexity: O(N2)
and places the elements in increasing order.
Time complexity: O(N2)
Approach:
1. Keep a variable mx which stores the maximum till ith element.
2. Iterate over the array and update,
mx = max(mx, a[i])
Iterations:
Code:
Sarasvati has an array of N non-negative integers. The i-th integer of the array is
Ai. She wants to choose a contiguous arithmetic subarray from her array that has
the maximum length. Please help her to determine the length of the longest
contiguous arithmetic subarray.
Input
The first line of the input gives the number of test cases, T. T test cases follow.
Each test case begins with a line containing the integer N. The second line
contains N integers. The i-th integer is Ai. Solution
Constraints Analysis
Output 1 sec = 108 operations
For each test case, output one line containing Case #x: y, where x is the test case 20 sec = 2x109 operations
number (starting from 1) and y is the length of the longest contiguous arithmetic
subarray. Intuition: We have to loop over the array and find the answer.
Constraints Steps
Time limit: 20 seconds per test set. 1. While iterating in the array we need to maintain the following variables,
Memory limit: 1GB. a. Previous common difference (pd) - To compare it with current
1 ≤ T ≤ 100. common difference (a[i] - a[i-1]).
0 ≤ Ai ≤ 109. b. Current arithmetic subarray length (curr) - It denotes the arithmetic
Test Set 1 subarray length including a[i].
2 ≤ N ≤ 2000. c. Maximum arithmetic subarray length (ans) - It denotes the max.
Test Set 2 Arithmetic subarray length till a[i].
2 ≤ N ≤ 2 × 105 for at most 10 test cases. 2. While iterating, there will be two cases,
For the remaining cases, 2 ≤ N ≤ 2000. a. pd = a[i] - a[i-1]
i. Increase curr by 1
ii. ans = max(ans, curr)
3. After loop ends, output the answer. (stored in ans variable).
Code
Arrays Challenge-Record Breaker Test set 2
Isyana is given the number of visitors at her local theme park on N consecutive
days. The number of visitors on the i-th day is Vi. A day is record breaking if it
satisfies both of the following conditions:
● The number of visitors on the day is strictly larger than the number of
visitors on each of the previous days.
● Either it is the last day, or the number of visitors on the day is strictly larger
than the number of visitors on the following day.
Note that the very first day could be a record breaking day!
Please help Isyana find out the number of record breaking days.
Solution
Input
Constraints Analysis
The first line of the input gives the number of test cases, T. T test cases follow. 1 sec = 108 operations
Each test case begins with a line containing the integer N. The second line 20 sec = 2x109 operations
contains N integers. The i-th integer is Vi .
Brute Force Approach
Output Iterate over all the elements and check if it is record breaking day or not.
For each test case, output one line containing Case #x: y, where x is the test case
number (starting from 1) and y is the number of record breaking days. Note: To check if a[i] is a record breaking day, we have to iterate over a[0],
a[1],...., a[i-1].
Constraints
1 ≤ T ≤ 100.
0 ≤ Vi ≤ 2 × 105.
Test set 1
1 ≤ N ≤ 1000.
Optimised Approach
Intuition: If we can optimise step (1), then we can optimise our overall solution.
For step (1): We need to check if a[i] > { a[i-1], a[i-2],..., a[0] }, which is same as
a[i] > max(a[i-1], a[i-2],..., a[0])
For this, we will keep a variable mx, which will store the maximum value till a[i].
Then we just need to check,
a[i] > mx
a[i] > a[i+1] , { if i+1 < n }
and update mx, mx = max(mx, a[i])
So step (1) time complexity reduces to O(1).
Overall time complexity: O(n)
Code
Arrays Challenge-Sum of all Subarrays
Question
Given an array a[] of size n. Output sum of each subarray of the given array. Dry Run
Idea: Iterate over all subarrays and output the sum after each iteration.
Approach
1. Write a nested loop, where outer loop runs from i=0 to i=n-1 and inner loop
runs from j=i to j=n-1.
2. Keep a curr variable which stores the sum from i to j.
3. Output curr after each iteration of inner loop. After inner loop ends, update
curr = 0.
This question tells us how to iterate over all the subarrays. This idea is very useful
in many questions which deals with operations on subarrays.
Code
Subarray v/s Subsequence Remember: Every subarray is a subsequence but every subsequence is not a
subarray.
Subarray
Subarray is a continuous part of the array.
Subsequence
A subsequence is a sequence that can be derived from an array by selecting zero
or more elements, without changing the order of the remaining elements.
Subsequences of the above array are: {}, {1}, {2}, {2}, {1,2}, {1,2}, {2,2}, {1,2,2}.
:
Arrays Challenge - Smallest Positive Missing Number
(Amazon, Samsung, Snapdeal, Accolite)
Iterations
Problem
Find the smallest positive missing number in the given array.
Example: [0, -10, 1, 3, -20], Ans = 2
Intuition
If in O(1), we can tell if an element is present in an array, then our task will be
simpler.
For that, we will maintain a Check[ ] array, that will if an element x is present in
the array or not.
It will be of boolean type as we only need to check the presence or absence of the
number.
Steps to Solve:
1. Build the Check[ ] array initialized with False at all indices.
2. By iterating over the array and marking non-negative a[i] as true i.e.
if(a[i] >= 0)
check[a[i]] = True
3. Iterate in the Check[ ] from i=1, BREAK the loop when you find check[i] =
False and store that i in the ans variable.
4. Output the ans.
Example:
(Amazon, Oracle)
Problem
Given an array arr[] of size N. The task is to find the first repeating element in an
array of integers, i.e., an element that occurs more than once and whose index of
first occurrence is smallest. Iterations
Constraints
1 <= N <= 106
0 <= Ai <= 106
Example
Input:
7
1534356
Output:
2
Explanation:
5 is appearing twice and its first appearance is at index 2 which is less than 3
whose first occurring index is 3.
Solution
Base idea: To check if an element is repeating, we maintain an array idx[], which
stores the first occurrence (index) of a particular element a[i].
Steps
1. Initialise the idx[] with -1, and minidx with INT_MAX.
Arrays Challenge-Subarray with given sum 5. Whenever the condition (currSum = S) is satisfied, store st and en and
BREAK from the loop.
(Google, Amazon, Facebook, Visa)
Time Complexity: O(n)
Problem
Given an unsorted array A of size N of non-negative integers, find a continuous Iterations
subarray which adds to a given number S.
Constraints
1 <= N <= 105
0 <= Ai <= 1010
Example
Input:
N = 5, S = 12
A[] = {1,2,3,7,5}
Output: 2 4
Explanation: The sum of elements from 2nd position to 4th position is 12.
Solution
Brute Force Solution
● Find sum of all possible subarrays. If any of the sum equates to S, output
the starting and ending index of the subarray.
Time Complexity : O(n2)
Optimized Approach
Steps:
1. Keep the pointers st and en, and a variable currSum that stores the sum
from st to en.
2. initialize st = 0, en = 0
3. Increment en till currSum + a[en + 1] > S
4. When 3rd condition occurs, start increasing st until currSum <= S.
Code:
Array Challenges Part 3 2. Prefix Sum Technique:
Idea: For each subarray arr[i..j], calculate its sum. Using prefix sum can
Maximum Sum Subarray Array reduce time to calculate the sum of arr[i..j] to O(1)
1. Brute Force: Time Complexity: O(N2)
Idea: For each subarray arr[i..j], calculate its sum. Space Complexity: O(N)
Time Complexity: O(N3)
Space Complexity: O(1)
3. Kadane’s Algorithm: Maximum Sum Circular Subarray:
Idea: Start taking the sum of the array, as soon as it gets negative, discard
the current subarray, and start a new sum.
Idea: There will 2 cases,
Time Complexity: O(N)
Space Complexity: O(1)
To get the Min subarray we multiply the array by -1 and get the maximum sum
subarray.
Time Complexity: O(N)
Pair Target Sum Problem
Find whether there exist 2 numbers that sum to K.
Important: The Array should be sorted for two pointer approach.
Idea: keep a low and high pointer, decide which pointer to move on the basis of
arr[low] + arr[high].
Time Complexity: O(N)
Space Complexity: O(1)
2 Dimensional Arrays
Notes
i.
1. It is similar to 2D matrices that we studied in 11th and 12th class.
ii.
iii.
2. It has 2 parts
a. Rows - Horizontal Arrays in the 2D matrix. For instance, in the above
example, we have 3 rows:
i. iv.
ii.
iii.
b. Columns - Vertical Arrays in the 2D matrix. For instance, in the above v.
example, we have 5 columns: 3. Note: Indexing of both rows and columns starts with 0.
Declaration of 2D matrices Searching in a matrix
1. 2D Arrays are declared similar to 1D arrays but with an additional
Problem: We have to find if value x is present in the 2D array.
dimension.
Syntax: int arr[rows][columns] 1. While traversing in the 2D matrix, just we have to put one if statement which
For example, checks if(a[i][j] == x) , then x is present otherwise not.
Code:
Code:
d. column_end - initialized with m-1.
2. First of all, we will traverse in the row row_start from column_start
Spiral Order Matrix Traversal to column_end and we will increase the row_start with 1 as we have
Problem: We have to print the given 2D matrix in the spiral order. Spiral traversed the starting row.
Order means that firstly, first row is printed, then last column is printed, 3. Then we will traverse in the column column_end from row_start to
then last row is printed and then first column is printed, then we will come row_end and decrease the column_end by 1.
inwards in the similar way. 4. Then we will traverse in the row row_end from column_end to
column_start and decrease the row_end by 1.
For example: for the given matrix, 5. Then we will traverse in the column column_start from row_end to
row_start and increase the column_start by 1.
6. We will do the above steps from 2 to 5 until row_start <= row_end
and column_start <= column_end.
Code: Input the array first then perform the following code
int m ain() {
Constraints int N = 3;
1 <= N <= 1000 int A[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
N=3
//print transpose
for(int i=0; i<N; i++) {
Sample Output1 for(int j=0 ;j<N; j++) {
A=[ cout << A[i][j] << " ";
}
[1,4,7],
cout << "\n";
[2,5,8], }
[3,6,9] return 0;
}
]
Approach
Time complexity : O(N2)
Transpose of a matrix means swapping its rows with columns & columns
Space complexity : O(1), as no extra space for a new matrix was used
with rows. But this swap is to be done only for the upper triangle of a matrix
Challenge 2 - Matrix Multiplication Approach
1. Make a nested loop of order 3. In the outer loop iterate over rows of
Problem the first matrix and in the inner loop iterate over columns of the
Given two 2-Dimensional arrays of sizes n1Xn2 and n2Xn3. Your task is to second matrix.
multiply these matrices and output the multiplied matrix. 2. Multiply rows of the first matrix with columns of the second matrix in
the innermost loop and update in the answer matrix.
Constraints
Dry Run
1 <= n1,n2,n3 <= 1,000
First Iteration
Second Iteration
3X4 4X3
Output
Third Iteration Sixth Iteration
Eighth Iteration
Fifth Iteration
Ninth Iteration Code
void multiplyMatrices()
{
int n1,n2,n3;
cin >> n1 >> n2 >> n3;
int m1[n1][n2]; int m2[n2][n3]; int ans[n1][n3];
for(int i=0; i<n1; i++) {
for(int j=0; j<n2; j++)
cin >> m1[i][j];
}
for(int i=0; i<n2; i++) {
for(int j=0; j<n3; j++)
cin >> m2[i][j];
}
for(int i=0; i<n1; i++) {
for(int j=0; j<n3; j++)
ans[i][j] = 0;
}
Note: We declare an array of n+1 as 0 to n-1 indices store the actual string and racecar racecar
nth character stores ‘\0’ (null character).
Algorithm:
Taking input and Printing output 1) Let the length of the character array be n.
2) Keep a boolean variable ans to store the result and initialize it with true.
2) Iterate over the string and check if ith character is equal to (n-i-1)th, there can be
2 cases
a) If equal, then do nothing
b) If unequal, then put ans = false
3) When the loop ends, if ans is true, then the string is palindrome else it is not a
palindrome.
Code:
We can also directly take input if there are no spaces between the characters in
the word
cin >> arr;
In the similar way, we can output the character array
cout << arr;
2. Largest word in a sentence
To input a complete sentence, we use the getline() function.
cin.getline(arr, n)
where arr is the character array and n is the total length of sentence.
Approach
1. Iterate over the sentence and keep variables currLen and maxLen which
store the current length of the present word being iterated and the overall
maximum length word’s length.
2. Whenever we encounter a space during iteration, we will maximize our
maxLen variable.
maxLen = max(maxLen, currLen)
Code
Pointers
Pointers are variables that store the address of other variables. Array Pointers
In C++, The name of the array is a pointer that points to the first element of the
Syntax array.
‘&’ Operator: It gives the address of the variable. Swapping 2 variables using the address
‘*’ Operator: It gives the value stored at the address, i.e dereferences the value Address of ‘a’ and ‘b’ gets interchanged, thus their values get swapped.
stored at the address
Working Demo
Delete Operator
To de-allocate a memory p, we pass its address to the delete() function.
New Operator:
New operator is used to allocate a block of memory of the given data type.
Dangling Pointer
If the memory location pointed by the pointer gets freed/ deallocated, then the
pointer is known as the Dangling Pointer.
Practise Question:
1. Declare a 2D array Dynamically.
2. Declare a 3D array Dynamically.
3. MCQs on Dynamic Memory Allocation.
Code:
String Challenges
Challenge 1
UpperCase-LowerCase interconversion
Given a string s with both uppercase and lowercase latin characters (‘a’ - ‘z’). Your
task is convert whole string into
1. Lower Case
2. Upper Case
2. UpperCase to LowerCase
Approach
1. Iterate over the string s and if s[i] is a upper case character, then update
s[i] +=32
Challenge 2 Challenge 3
Form the biggest number Max Frequency
Given a string of integers, our task is to form the biggest number out of those Given a string s of latin characters, your task is to output the character which has
numbers in the string. maximum frequency.
Approach: Approach:
Sort the string in descending order using inbuilt sort function. Maintain frequency of elements in a separate array and iterate over the array and
find the maximum frequency character.
Code
Code
Challenge 4 (Additional Question)
Compression of strings
Given a string s, your task is to remove the repeating consecutive characters.
Approach: Create an answer string and iterate in the string from i=1 and check if it
is equal to the previous character. Two cases arise
1. s[i] = s[i-1] - then do not push_back the ith character to the answer string.
2. s[i] != s[i-1] - then push_back the ith character to the answer string.
Code
Bit Manipulation - I Toggle ith bit
Mask: 1 << i
Prerequisites: knowledge of binary number system Bitwise XOR operation between n and mask toggle the ith bit.
Input: 6
Swap 2 numbers using bit operations:
Output: 7 a ^= b;
b ^= a;
Equal Sum and XOR ^= b
a ;
Problem: Given a positive integer n, find count of positive integers i such that 0 <=
i <= n and n+i = n⊕i (⊕ is the XOR operation)
Instead of using looping (Brute force method), we can directly find it by a Flip the bits of a number:
mathematical trick i.e. It can be done by a simple way, just simply subtract the number from the value
obtained when all the bits are equal to 1 .
Let x be the number of unset bits in the number n. For example:
Answer = 2x Number: Given Number
Value : A number with all bits set in a given number.
XOR of all subsequences of an array Flipped number = Value – Number.
The answer is always 0 if the given array has more than one element. For an array
with a single element, the answer is the value of the single element. Example :
Logic: If the array has more than one element, then element occurs. Number = 23,
Binary form: 10111
Number of leading zeros, trailing zeroes and number of 1’s of a number After flipping digits number will be: 01000
It can be done by using inbuilt function i.e. Value: 11111 = 31
Number of leading zeroes: builtin_clz(x)
We can find the most significant set bit in O(1) time for a fixed size integer. For
example below code is for a 32-bit integer.
n |= n>>2;
n |= n>>4;
= n>>8;
n |
n |= n>>16;
n = n + 1
;
return (n >> 1);
}
Practice questions:
1. Reverse bits
2. Hamming distance
Bit Manipulation - II Generate Subset
Explanation: if the jth bit is set, then we take the jth element.
Prerequisites: knowledge of binary number system There are a total of 2n subsets.
Practice Questions:
1. Counting bits
2. Power of four
Power of two
From our past knowledge of the binary number system,
Numbers of the type 2n have only 1 set bit.
Explanation: n = 000100
n - 1 = 000011
n & ( n - 1 ) = 000000
!( n & ( n - 1 ) ) = 000001
If the number only had one set bit, then n & ( n - 1 ) would be zero.
Bit Manipulation Challenges Challenge 2
Q2. Write a program to find 2 unique numbers in an array where all numbers
except two, are present twice.
Challenge 1
Write a program to find a unique number in an array where all numbers except Logic
one, are present twice. 1. Take XOR of all the elements and let that xor value be x. All the repeating
Hint: A ⊕ B ⊕ B ⊕ A ⊕ C = C. All those numbers which occur twice will get nullified elements will get nullified and xor of only two unique elements will last. (as
after ⊕ operation. a⊕a = 0).
2. There will be at least one bit set in x. Using that set bit, divide the original
Sample Test Case: set of numbers into two sets
Input: a. First set which contains all the elements with that bit set.
b. Second set which contains all the elements with that bit unset.
3. Take xor of both the sets individually, and let those xor values be x1 and x2.
Output: 4 4. Voila, x1 and x2 are our unique numbers. Reason: both the above sets
Code contain one of the unique elements and rest elements of the sets occur
#include<iostream> twice which will get nullified after ⊕ operation.
using namespace std;
int unique(int arr[], int n) {
Sample Test Case:
int x orsum = 0;
for (int i = 0
; i < n; i++) { Input:
xorsum = xorsum ^ arr[i];
}
return xorsum;
} Output: 5 7
int main() {
int arr[] = {1, 2, 3, 4, 1, 2, 3};
cout << unique(arr, 7) << endl;
return 0;
}
Challenge 3
Q3. Write a program to find a unique number in an array where all numbers
Code except one, are present thrice.
#include<iostream>
using namespace std;
Sample Test Case:
int setBit(int n
, int pos) {
return ((n & (1 << pos)) != 0); Input:
}
void u nique(int arr[], int n) {
int xorsum = 0;
for (int i = 0; i < n; i++) {
Output: 4
xorsum = xorsum ^ a rr[i];
}
int tempxor = xorsum; Logic
int setbit = 0; 1. We will maintain an array of 64 size which will store the number of times ith
int pos = 0;
bit has occurred in the array.
while (setbit != 1) {
setbit = xorsum & 1;
pos++;
xorsum = xorsum >> 1; 2. Take the modulo of each element of this array with 3. Resultant array will
} represent the binary representation of the unique number.
nt newxor = 0
i ;
3. Convert that binary number to decimal number and output it.
for (int i = 0; i < n; i++) {
if (setBit(arr[i], pos - 1)) {
newxor = newxor ^ arr[i];
}
}
cout << newxor << endl;
cout << (tempxor ^ newxor) << endl;
}
int main() {
int arr[] = {1, 2, 3, 1, 2, 3, 5, 7};
unique(arr, 8)
;
return 0;
}
Code
#include<iostream>
using namespace std;
Additional Question:
Find primes in the given range
GCD (Greatest Common Divisor)
Number Theory Basics
In our childhood, we used to call it HCF (Highest Common Factor). GCD of two
numbers is the largest number that divides both of them.
Inclusion Exclusion principle
In many questions, we are required to include contributions of more than one Idea
term in our answer. This results in inclusion of the same term more than once, We use the logic that
hence we use the principle of inclusion exclusion. gcd(a,b) = gcd(b,a%b)
Question Code
#include<iostream>
Find the number of numbers in the interval [1,n] which are divisible by a or b.
using namespace std;
int main(){
int c1=n/a;
int c2=n/b; int a,b;
int c3=n/(a*b);
cin>>a>>b;
return c1+c2-c3;
}
cout<<gcd(a,b)<<endl;
return 0;
int main(){
}
int n, a, b;
cin>>n>>a>>b;
cout<<divisible(n,a,b)<<endl;
return 0;
}
Recursion - I Print the numbers in the sequence:
Objectives:
Sum till n 1. Print the number in increasing order up to n.
Objective: To get the sum of the first n number using recursion. 2. Print the number in decreasing order from n to 1.
Base Case : If n == 0: Approach:
return 0; For increasing order, we first print the remaining numbers using recursion and
We add the current number and recurse for Sum(n-1) then print the current number.
Time Complexity: O(N) For decreasing order, we first print the current number and then print the
Space Complexity: O(N) remaining number using recursion.
Time Complexity: O(N)
Space Complexity: O(N)
Fibonacci Factorial
Objective: To get the Fibonacci of n Objective: To get the factorial of the n
Recurrence Relation: F(n) = F(n-1) + F(n-2) Base Case : If n == 0:
Base Case : If (n == 0 or n == 1): //Since F(n) depends on prev two states return 1;
return n; //so base case will have two cases We multiply the current number and recurse for factorial(n-1)
We calculate fib(n - 1), fib(n - 2) using recursion, and return the sum of the two Time Complexity: O(N)
Time Complexity: O(N) Space Complexity: O(N)
Space Complexity: O(N)
To calculate np using Recursion
Objective: To calculate pth power of n i.e. np .
Base Case : If p == 0:
return 1;
We multiply the current number and recurse for power(n, p - 1)
Time Complexity: O(N)
Space Complexity: O(N)
Recursion - 1.2
Print in increasing and decreasing order Find the first and last occurrence of an element using recursion
Objective: To print numbers 1 to n, in increasing as well as decreasing order. Objective: To find the first occurrence, we return as soon as we find the element.
We have to do two things, 1. Recurse for the remaining number To find the last occurrence, we return the result we get from further function
2. Print the numbers calls.
Base Case : If n == 1: Base Case would be when you reach the end of the array.
print(1) Time Complexity: O(N)
return; Space Complexity: O(N) for function call stack
int firstocc(int arr[], int n, int i, int key) {
if (i == n) {
Time Complexity: O(N) return -1;
Space Complexity: O(N), for the call stack }
void dec(int n) { if (arr[i] == key) {
if (n == 1 ) { return i;
cout < < "1" << endl; }
return; return firstocc(arr, n, i + 1, key);
} }
cout << n << endl; int lastocc(int a rr[], int n, int i, int key) {
dec(n - 1); if (i == n) {
} return -1;
void i nc(int n
) { }
if (n == 1 ) { int restArray = lastocc(arr, n, i + 1, key);
cout < < "1" << endl; if (restArray != -1) {
return; return restArray;
} }
inc(n - 1 ); if (arr[i] == key) {
cout << n << endl; return i;
} }
eturn -1;
r
}
Check if Array is Sorted [Strictly increasing]