50% found this document useful (2 votes)
497 views116 pages

Apna Collage Final

This document provides an outline for a course on data structures and algorithms. It covers topics like arrays, sorting, recursion, linked lists, stacks, queues, binary trees, and binary search trees. The course is divided into 9 weeks and includes 37 sections covering key concepts, data structures, algorithms, and example problems.

Uploaded by

VINEET
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
50% found this document useful (2 votes)
497 views116 pages

Apna Collage Final

This document provides an outline for a course on data structures and algorithms. It covers topics like arrays, sorting, recursion, linked lists, stacks, queues, binary trees, and binary search trees. The course is divided into 9 weeks and includes 37 sections covering key concepts, data structures, algorithms, and example problems.

Uploaded by

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

- Introduction to arrays

Index - Linear search and Binary search


(Started from 8th October 2020) - Sorting algorithms
- STL sort
1. Understanding computer programs (First week - 8/10/2020 - 14/10/2020) - Max subarray sum
- What is computer program and algorithm - Pair sum problem
- What is flowchart
- What is pseudocode 9. 2D arrays (Third week)
- Examples - Introduction and searching
- Setting up c++ environment - Example questions
- Hello world program
- Brain teasers 10. Character arrays (Fourth week 29/10/2020 - 4/11/2020)
- Introduction and input
2. Programming Fundamentals l (First week) - Palindromic arrays
- Data Types and ranges - Largest word in a string
- Type modifiers
- Input output in C++ 11. Strings (Fourth week)
- If else - Intro + STL functions on strings
- Loops - while, do while, for - Sorting a string

3. Programming Fundamentals ll (First week)


- Break and continue 12. Questions (Fourth week)
- Switch - Target sum triplets
- Operators - arithmetic, relational, logical, bitwise, assignment (https://www.geeksforgeeks.org/find-a-triplet-that-sum-to-a-given-value/)
- Max circular sum
4. Pattern Questions (Second week 15/10/2020 - 21/10/2020) (https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/)
- Introductory examples - String questions
- Difficult examples
13. Pointers (Fourth week)
5. Basics of Number System (Second week) - & operator
- Binary number system - Introduction to pointers
- Reverse a number - Dereference operator
- Armstrong number - Pass by reference and Pass by value
- Prime numbers
14. Dynamic Memory Allocation (Fourth week)
6. Functions (second week) (Second week) - Compile time and run time
- Introduction to functions - Heap and Stack
- Examples - New, delete

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

30. Stacks (Seventh week) 36. Questions (Eighth week)


- Introduction - Build from inorder and preorder
- Implement using array - Sum at level K
- Implement using linked list - Sum replacement problem
- Reverse a stack - Maximum sum path
- Balanced parenthesis - Shortest distance between nodes

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

33. Deque (Seventh week) 38. Questions (Ninth week)


- Introduction - Structurally identical BST
- Maximum element - ZigZag order
- Max length unique character substring - Largest BST in BT

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

54. Questions (​Thirteenth week)


- Intersection of 2 arrays
- String window
- Subarrays with distinct element
- Digital dictionary

55. String algorithms (​Thirteenth week)


- Brute force
- KMP
- Finite automata
- Robin karp

56. Segment tree (Fourteenth week 7/01/2021 - 13/01/2021)


- Intro, build, updation, query
- Min, max, sum in the subarray
- Lazy propagation

57. Binary indexed tree (Fourteenth week)


- Structure of BIT
- Update or build, query.
- Problems

58. Mo’s (sqrt decomposition) (Fifthteenth week 14/01/2021 - 20/01/2021)


- Offline processing of queries with examples
- Introduction, code and examples

59. HLD (Fifthteenth week)


60. Fourier series (Fifthteenth week)
specific which means that the machine code used to run a program on one specific
Introduction to Programming Languages computer needs to be modified to run on another computer.

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:

10101011100001110100111101 A little about C++ language

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

Pseudocode is a method of describing computer algorithms using a combination of


Algorithm natural language and programming language. It is essentially an intermittent step towards
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in the development of the actual code. It allows the programmer to formulate their thoughts
a certain order to get the desired output. Algorithms are generally created independent of on the organization and sequence of a computer algorithm without the need for actually
underlying languages, i.e. an algorithm can be implemented in more than one programming following the exact coding syntax.
language.

Qualities of a good algorithm Examples –


1. Input and output should be defined precisely. Ques1. Write a flowchart and pseudocode for finding the sum of 2 numbers.
2. Each step in the algorithm should be clear and unambiguous.
3. An algo i hm ho ldn incl de comp e code In ead he algo i hm ho ld be
written in such a way that it can be used in different programming languages.

Good, logical programming is developed through good pre-code planning and


organization. This is assisted by the use of pseudocode and program flowcharts.

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.

Data Type Meaning Size (in Bytes)

int Integer 4

float Floating-point 4

double Double Floating-point 8

char Character 1

wchar_t Wide Character 2

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.

Data Type Size (in Bytes) Meaning

signed int 4 used for integers (equivalent to int)

unsigned int 4 can only store positive integers

short 2 used for small integers (range -32768 to 32767)

long at least 4 used for large integers (equivalent to long int)

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)

long double 8 used for large floating-point numbers

signed char 1 used for characters (guaranteed range -127 to


127)
unsigned char 1 used for characters (range 0 to 255)

Derived Data Types


These are the data types that are derived from fundamental (or built-in) data
types. For example, arrays, pointers, function, reference.

User-Defined Data Types


These are the data types that are defined by user itself.
For example, class, structure, union, enumeration, etc.

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.
}

Input and Output in C++


1. Comments
The two slash(//) signs are used to add comments in a program. It does
not have any effect on the behaviour or outcome of the program. It is The header file iostream must be included to make use of the input/output
used to give description of the program you’re writing. (cin/cout) operators.

2. #include<iostream> Standard Output (cout)


#include is the pre-processor directive that is used to include files in our By default, the standard output of a program points at the screen. So with the
program. Here we are including the iostream standard file which is cout operator and the “insertion” operator ( ) you can print a message onto
necessary for the declarations of basic standard input/output library in the screen.
C++.
#include<iostream>
3. Using namespace std
using namespace std;
All elements of the standard C++ library are declared within namespace.
Here we are using std namespace.
int main()
4. int main()
{
The execution of any C++ program starts with the main function, hence it
is necessary to have a main function in your program. ‘int’ is the return cout << "Hello World!";
value of this function. (We will be studying about functions in more detail return 0;
later).
}
5. {} To print the content of a variable the double quotes are not used.
The curly brackets are used to indicate the starting and ending point of
any function. Every opening bracket should have a corresponding closing #include<iostream>
bracket.
using namespace std; The cout operator does not put a line break at the end of the output. So if
you want to print two sentences you will have to use the new-line character
( \n ).
int main()
{
char Yes = 'y'; cout << "This is one sentence.\n";
cout << Yes; cout << "This is another.\n";
return 0;
}

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.)

The cin operator is also chainable. For example:

cin >> X >> Y;

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 () { #include <iostream>


int age ; using namespace std ;
cin >> age ;
int main () {
if ( age >= 18 ) { int x,y ;
cout << "You can vote." ; cin >> x >> y ;
}
else { if ( x == y ) {
cout << "Not eligible for voting." ; cout << "Both the numbers are equal" ;
} }
else {
return 0 ; if ( x > y ) {
} cout << "X is greater than Y" ;
}
else {
else if cout << "Y is greater than X" ;
}
To specify multiple if conditions, we first use if and then the consecutive }
statements use else if.
return 0 ;
}
#include <iostream>
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){

using namespace std; max=n1;


min=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.

#include<iostream> int main(){


using namespace std;

int a,b,c;
int main(){ cin>>a>>b>>c;

int n1,n2; if(a>b){


if(a>c){ cout << "Input three sides of triangle: \n ";

cout<<a<<endl; cin >> sidea >> sideb >> sidec;

}
else{ if (sidea == sideb && sideb == sidec)

cout<<c<<endl; {

} cout << "This is an equilateral triangle. \n ";


}
}
else if (sidea == sideb || sidea == sidec || sideb == sidec)
else{
{
if(b>c){
cout << "This is an isosceles triangle. \n ";
cout<<b<<endl;
}
}
else
else{
{
cout<<c<<endl;
cout << "This is a scalene triangle. \n ";
}
}
}

return 0;
return 0;
}
}

5. Program to check if an alphabet is a vowel or a consonant.


4. Program to check if a triangle is scalene, isosceles or equilateral.

#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;

isLowercaseVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');

isUppercaseVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');

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.

for loop while loop

The syntax for while loop is


The syntax of the for loop is

for (initialization; condition; update) {


while (condition) {
// body of-loop
// body of the loop
}
}

#include<iostream> #include<iostream>

using namespace std; using namespace std;

int main(){ int main(){

for(int i=1;i<=5;i++){ int i=1;

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 main(){ int n;


cin>>n;
int i=1;

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;

cout << "Enter a positive integer: ";


return 0;
cin >> n;
}

for (int i = 1; i <= 10; ++i) {


cout << n << " * " << i << " = " << n * i << endl;
}

return 0;
}

Ques3. Program to add only positive numbers.

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

cout << "Enter a number: ";


cin >> number;
Jumps in Loops Examples
Ques1. Write a program to print all odd numbers till n.

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;

for (int num=a; num<=b; num++) {


int i;
for (i=2; i<num; i++) {
if (num%i==0) { //it is not prime
break;
}
}
if (i==num) { //loop has completed all iterations
cout<<num<<endl;
}
}

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;

switch (n) int main() {


{
case 1: // code to be executed if n == 1; int n1,n2;
break;
char op;

cout<<"Enter 2 numbers: ";


case 2: // code to be executed if n == 2; cin>>n1>>n2;
break;
cout<<"Enter operand: ";
default: // code to be executed if n doesn't match any of the above cases
cin>>op;
}
switch (op)
{

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;
}

Ques2. Write a program to find whether an alphabet is a vowel or a consonant.

#include <iostream>
using namespace std;

int main() {

char c;

cout<<"Enter an alphabet: ";


cin>>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;

Suppose : A=5 and B=10 Output : 11 11

Operator Operation Example

+ Adds two operands A+B = 15


2. Relational Operators
Relational operators define the relation between 2 entities.
- Subtracts right operand from left operand B-A = 5 They give a boolean value as result i.e true or false.
* Multiplies two operands A*B = 50
Suppose : A=5 and B=10
/ Divides left operand by right operand B/A = 2
Operator Operation Example
% Finds the remainder after integer division B%A = 0
== Gives true if two operands are equal A==B is not
++ Incrementer A++ = 6
true
-- Decrementer A-- = 4
!= Gives true if two operands are not equal A!=B is true

> 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.

Suppose : A=5(0101) and B=6(0110)

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

<< Bi a Lef Shif The lef e a d bi a e ed 4 (0100)


Example - left by the number of places specified by the right 4<<1
operand. =1000 = 8
>> Bi a Righ Shif O e a The lef e a d bi a e 4>>1 Condition? Conditional operator. If condition is true, A+=B means A =
moved right by the number of places specified by the =0010 = 2 X:Y then returns value of X or else value of Y A+B
right operand.
Cast Casting operators convert one data type to int(4.350) would
another. return 4.
If shift operator is applied on a number N then,
Comma (,) Comma operator causes a sequence of
N<<a will give a result N*2^a operations to be performed. The value of
N>>a will give a result N/2^a the entire comma expression is the value of
the last expression of the comma-separated
list.

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

Bitwise AND & Left to right


6. Misc Operators
Bitwise XOR ^ Left to right

Operator Operation Example Bitwise OR | 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 }

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left Ans. 3


(Priority for the values inside a brackets () assigned to any variable is
Comma , Left to right given from 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;

int main() (x & 1) ? printf("true") : printf("false");

{ 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 main() printf("%d",3 * 2--);

{ }

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​ ​++)


#i c de ​<i ea > ​ f ​(​i ​j ​= ​1​; ​j ​<= ​c ​ j
; ​ ​++)
​if ( ​ ​i ​== ​1 ​ ​i ​== ​ ​ ​ ​== ​1 ​
j ​j ​== ​c ​)
i g a e ace ​ d​; ​c ​<< ​"*"​;
​e e ​
i ​ ai ​() ​c ​<< ​" "​;
​i ​ ​, ​c ​;
​ c ​<< ​"E e he be f :​\ ​"​;
​ci ​>> ​ ​; ​c ​<< ​e d ;
​c ​<< ​"E e he be f c :​\ ​"​;
​ci ​>> ​c ​; ​ e ​0​;

​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 ​>> ​ ​;

​f ​(​i ​i ​= ​ ​; ​i ​>= ​1​; --​i​)


​f ​(​i ​i ​= 1
​ ​; ​i ​<= ​ ​; ++​i​)
​ f ​(​i ​ ​= ​1​; ​j ​<= ​i​; ++​j​)
j
​ f ​(​i ​ ​= ​1​; ​j ​<= ​i​; ++​j​)
j
​ c ​ < ​j ​<< ​" "​;
<
​ c ​ < ​j ​<< ​" "​;
<

​c ​<< ​e d ;
​c ​<< ​"​\ ​"​;

​ e ​0​;
​ e ​0​;

Print Half Pyramid using numbers - 2

#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​;

Print Inverted Half Pyramid using numbers - 2


#i c de ​<i ea >

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​;

int​ ​main​(){ ​return​ ​0​;


​f ​(​i ​j ​= ​1​; ​j ​<= ​ ace​; ​j​++)
​ c ​<< ​" "​;

​f ​(​i ​j ​= ​1​; ​j ​<= ​2 ​* ​i ​- ​1​; ​j​++)


​ c ​<< ​"*"​;

​c ​<< ​e d ;
​ ace​--;

​ ace ​= 0
​ ​;
​f ​(​i ​ ​= ​ ​; ​i ​>= ​1​; ​i​--)
i
​f ​(i ​ ​ ​= ​1​; ​j ​<= ​ ace​; ​j​++)
j

Advanced Pattern Problems ​c ​ < ​" "​;


<

​f ​(​i ​j ​= ​1​; ​j ​<= ​2 ​* ​i ​- ​1​; ​j​++)


​ c ​<< ​"*"​;
Print Diamond using Stars : Given n, print diamond with 2*n rows.
​c ​<< ​e d ;
​ ace​++;

​ e ​0​;

Print Hollow Diamond using Stars

#i c de ​<i ea >

i g a e ace ​ d​;

i ​ ai ​()
​i ​ ​;
​ci ​>> ​ ​;

​i ​ ace ​= (​2 ​* ​ ​- 1 ​ ​) / ​2​;


#i c de ​<i ea >
​ f ​(​i ​i ​= ​1​; ​i ​<= ​ ​; ​i​++)
i g a e ace ​ d​;

i ​ ai ​() Print Hollow Diamond Inscribed in a Rectangle


​i ​ ​;
​ci ​>> ​ ​;

​i ​ ace ​= (​2 ​* ​ ​- ​1​) / ​2​;


​ f ​(​i ​i ​= ​1​; ​i ​<= ​ ​; ​i​++)
​f ​(​i ​j ​= ​1​; ​j ​<= ​ ace​; ​j​++)
​c ​<< ​" "​;

​f ​(​i ​j ​= ​1​; j​ ​<= ​2 * ​ i​ -​ 1​ ​; ​j​++)


​if ​(​j ​== ​1 ​ ​j ​== 2​ *​ i​ -​ ​1​)
​c ​<< "​ *"​;
​e e ​
​c ​<< ​" "​;

​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 ; ​f ​(​i ​j ​= ​1​; j​ ​<= ​2 * ​ i​ -​ 1​ ​; ​j​++)


​ ace​++; ​if ​(​j ​== ​1 ​ ​j ​== 2​ *​ i​ -​ ​1​)
​c ​<< "​ *"​;
​ e ​0​; ​e e ​
​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​;

​f ​(​i ​j ​= ​1​; j​ ​<= ​2 * ​ i​ -​ 1​ ​; ​j​++)


​if ​(​j ​== ​1 ​ ​j ​== 2​ *​ i​ -​ ​1​)
​c ​<< "​ *"​; Print Hollow Rhombus
​e e ​
​c ​<< ​" "​;

​f ​(​i ​j ​= ​1​; ​j ​<= ​ ace​; ​j​++)


​ c ​<< ​"*"​;

​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 ​ < ​" "​;
<

​f ​(​i ​j ​= ​1​; ​j ​<= ​ ​; ​j​++)


​if ​(​i ​== ​1 ​ ​i ​== ​ ​)
​c ​<< ​"*"​;
​e e ​
​if ​(​j ​== ​1 ​ ​j ​== ​ ​)
#i c de ​<i ea >
​c ​<< ​"*"​;
​e e ​
i g a e ace ​ d​;
​c ​<< ​" "​;

i ​ ai ​()
​i ​ ​;
​ci ​>> ​ ​;
​c ​<< ​"​\ ​"​;

​f ​(​i ​ ​= 1
i ​ ​; ​i ​<= ​ ;
​ ​i​++)
​ e ​0​;
​ f ​(​i ​ ​= ​1​; ​j <
j ​ = ​ ​- ​i​; ​j​++)
​ c ​ < ​" "​;
<

​f ​(​i ​j ​= ​1​; ​j ​<= ​ ​; ​j​++)


Pyramid pattern for Numbers Pyramid Pattern for Numbers - 2

#i c de ​<i ea >

i g a e ace ​ d​; #i c de ​<i ea >

i ​ ai ​() i g a e ace ​ d​;


​i ​ ​;
​ci ​>> ​ ​; i ​ ai ​()
​i ​ ​;
​i ​ ace ​= ​ ​- ​1​; ​ci ​>> ​ ​;
​ f ​(​i ​i ​= 1
​ ​; ​i ​<= ​ ;
​ ​i​++)
​f ​(​i ​ ​= ​1​; ​j <
j ​ = ​ ace​; ​j​++) ​i ​ ace ​= ​ ​- ​1​;
​c ​ < ​" "​;
< ​ f ​(​i ​i ​= 1
​ ​; ​i ​<= ​ ;
​ ​i​++)
​f ​(​i ​ ​= ​1​; ​j <
j ​ = ​ ace​; ​j​++)
​ ace​--; ​c ​ < ​" "​;
<
​f ​(​i ​ ​= ​1​; ​j ​<= ​i​; ​j​++)
j
​c ​ < ​i ​<< ​" "​;
< ​ ace​--;
​f ​(​i ​ ​= ​1​; ​j ​<= ​i​; ​j​++)
j
​c ​<< ​"​\ ​"​; ​c ​ < ​j ​<< ​" "​;
<

​ e ​0​; ​c ​<< ​"​\ ​"​;

​ e ​0​;
​f ​(​i ​j ​= ​1​; ​j ​<= ​e _ ace​; ​j​++)
Print Sold Butterfly Pattern ​ c ​<< ​" "​;

​f ​(​i ​j ​= ​1​; ​j ​<= ​i​; ​j​++)


​ c ​<< ​"*"​;

​c ​<< ​"​\ ​"​;

​ e ​0​;

Print Hollow Butterfly Pattern

#i c de ​<i ea >

i g a e ace ​ d​;

i ​ ai ​()
​i ​ ​;
​ci ​>> ​ ​;

​f ​(​i ​i ​= ​1​; ​i ​<= ​ ;​ ​i​++)


​ i ​e _ ace ​= 2 ​ ​* ​ ​- ​2 ​* ​i​;
​ f ​(​i ​j ​= ​1​; ​j < ​ = ​i​; ​j​++)
​ c ​<< ​"*"​;

​f ​(​i ​j ​= ​1​; ​j ​<= ​e _ ace​; ​j​++) #i c de ​<i ea >


​ c ​<< ​" "​;
i g a e ace ​ d​;
​f ​(​i ​j ​= ​1​; ​j ​<= ​i​; ​j​++)
​ c ​<< ​"*"​; i ​ ai ​()
​i ​ ​;
​c ​<< ​"​\ ​"​; ​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 ​<< ​" "​;

​f ​(​i ​j ​= ​1​; j​ ​<= ​i​; ​j​++)


​if ​(​j ​== ​1 ​ ​j ​== ​i​)
​c ​<< "​ *"​;
​e e ​
​c ​<< ​" "​;

​c ​<< ​"​\ ​"​; #i c de ​<i ea >

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*2​3 ​+ 1*2​2 ​+ 0*2​1 ​+ 1*2​0 ​ = 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 (10​0​)
1. 10001 (A = 17)
2. 11000001 (A = 193)
A , 152. 3. 111111111 (A = 511)
152
152 = 1*100 + 5*10 + 2*1
152 = 1*10​2​ + 5*10​1​ + 2*10​0 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 (2​0​) A N
A
. E. 153 = 1​3 ​+ 5​3​ + 3​3​ = 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 ​<< ​"​\ ​"​;

​ 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 ​>> ​ ​;

​c ​<< ​fac ​<< ​"​\ ​"​; ​i ​ e _ ​= ​0​;


​ e ​0​;
​ hi e ​(​ > ​ ​0​)
​i ​ e ​= ​ ​% ​10​;
​ e _ ​= ​ e _ ​* ​10 ​+ ​ e ​;
F 0,1 ​ ​= ​ ​/ ​10​;
#i c de ​<i ea >

i g a e ace ​ d​; ​c ​<< ​ e _ ​<< ​"​\ ​"​;

i ​ ai ​() ​ e ​0​;
​i ​ ​;
​ci ​>> ​ ​;

​if ​(​ ​== ​1​)


​c ​<< " ​ 0​\ ​"​;
​e e if ​(​ = ​ = ​2​)
​c ​<< ​"0 1​\ ​"​;
Prime Numbers
Prime numbers are numbers which have only 2 distinct factors i.e 1 and the #include <iostream>
using namespace std;
number itself. Eg. 2,3,5,7,19 etc. int main()
{
Armstrong Numbers int n;
cin >> n;
Armstrong numbers are numbers which have their sum of cube of individual while (n > 0)
digits equal to the number itself. {
E.g 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153. int rem = n % 10;
cout << rem << " \n ";
n = n / 10;
}
Practice Problems return 0;
}

Ques1. Write a program to check if a number is prime or not.


Ques3. Write a program to reverse a number
E.g Given a number 1879 we need to convert it to 9781.
#include <iostream>
#include<cmath> 100020 will be converted to 20001 (Note: We need to remove the trailing zeroes).
using namespace std;
#include <iostream>
using namespace std;
int main() {
int main() {
int n;
cin>>n;
int n;
cin>>n;
bool flag=0;
int reverse=0;
for(int i=2;i<=sqrt(n);i++){
while(n>0){
int lastdigit= n%10;
if(n%i==0){
reverse = reverse*10 + lastdigit;
cout<<"Non-prime"<<endl;
n=n/10;
flag=1;
}
break;
}
cout<<reverse<<endl;
}

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;
}

Some more practice questions

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.

Why are functions used?


Examples –
If some functionality is performed at multiple places in software, then
rather than writing the same code, again and again, we create a function Ques1. Write a program to add 2 numbers using functions.
and call it everywhere. This helps reduce code redundancy.
Functions make maintenance of code easy as we have to change at one
#include <iostream>
place if we make future changes to the functionality.
Functions make the code more readable and easy to understand. using namespace std;

The syntax for function declaration is-


int add(int num1, int num2){

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){

bool isPrime(int num){ int t1=0;


for(int i=2;i<=sqrt(num);i++){ int t2=1;
if(num%i==0){ int nextTerm;
return false;
} for(int i=1;i<=n;i++){
} cout<<t1<<endl;
return true; nextTerm=t1+t2;
} t1=t2;
t2=nextTerm;
int main(){ }
return;
int a,b; }
cin>>a>>b;

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;

using namespace std; }


return factorial;

int fact(int n){ }

int factorial=1;
for(int i=2;i<=n;i++){ int main(){

factorial*=i;
} int n,r;

return factorial; cin>>n>>r;

}
int ans = fact(n)/(fact(r)*fact(n-r));

int main(){ cout<<ans<<endl;

int n;
cin>>n; return 0;
}

int ans = fact(n);


cout<<ans<<endl;
Ques4. Write a program to print the Pascal triangle.
return 0;
}

#include<iostream>
Ques4. Write a program to find the binary coefficient (nCr)
using namespace std;

#include<iostream> int fact(int n){

using namespace std; int factorial=1;


for(int i=2;i<=n;i++){
factorial*=i; Ques9. Write a program with a function to swap the values of 2 given integer
variables.
}
return factorial; Ques10. Write a program using functions to check if a person is eligible for
} voting or not by comparing his age with legal voting age i.e. 18.

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.

Ques7. Write a program to find out whether a given character is an alphabet or


not 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

Quick questions on functions Binary to decimal


1) Sum of first n natural numbers
2) Check pythagorian triplet
3) Conversions
a) Binary to decimal
b) Octal to decimal
c) Hexadecimal to decimal
d) Decimal to binary Octal to decimal
e) Decimal to octal
f) Decimal to hexadecimal
4) Add two binary numbers

Sum of first n natural numbers

Check pythagorian triplet


Hexadecimal to decimal
Decimal to binary

Decimal to octal
Decimal to hexadecimal Add two binary numbers
Codes

1. Sum of first n natural numbers

2. Check pythagorean triplet


Conversions
c) Hexadecimal to decimals
a) Binary to Decimal

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

Space and Time Complexity

Time Complexity: O(n+m)

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:

Time complexity: O(log(n))

Comparison of functions on the basis of time complexity


It follows the following order in case of time complexity:
Linear Time Complexity. O(n) O(nn) > O(n!) > O(n3) > O(n2) > O(n.log(n)) > O(n.log(log(n))) > O(n) > O(sqrt(n)) > O(log(n)) > O(1)
Note: Reverse is the order for better performance of a code with corresponding time complexity, i.e. a program with less time complexity is more
efficient.

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.

Quadratic time Complexity. O(n2)


A a in C
An Array is a data structure used to store blocks of information in contiguous
memory allocation The data can be integer strings characters class objects etc
Decla ing an A a

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(N​2​)
and places the elements in increasing order.
Time complexity: O(N​2​)

Homework: ​Implement selection sort, bubble sort, insertion sort on


your own.
2. Bubble Sort:
Idea: if arr[i] > arr[i+1] swap them. To place the element in their respective
position, we have to do the following operation N-1 times.
Time Complexity: O(N​2​)
Arrays Challenge (Max till i)
Problem:
Given an array a[] of size n. For every i from 0 to n-1 output max(a[0], a[1],..., a[i]).

Approach:
1. Keep a variable mx which stores the maximum till i​th​ element.
2. Iterate over the array and update,
mx = max(mx, a[i])

Iterations:
Code:

Time Complexity: O(n).


Arrays Challenge-Longest Arithmetic Subarray
(Google kickstart)
Problem
An arithmetic array is an array that contains at least two integers and the
differences between consecutive integers are equal. For example, [9, 10], [3, 3, 3],
and [9, 7, 5, 3] are arithmetic arrays, while [1, 3, 3, 7], [2, 1, 2], and [1, 2, 4] are
not arithmetic arrays.

Sarasvati has an array of ​N​ non-negative integers. The i-th integer of the array is
A​i​. 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 ​A​i​. Solution
Constraints Analysis
Output 1 sec = 10​8​ operations
For each test case, output one line containing Case #x: y, where x is the test case 20 sec = 2x10​9​ 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 ≤ ​A​i​ ≤ 10​9​. 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 × 10​5​ 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

(Google kickstart) 1 ≤ ​N​ ≤ 2 × 10​5​ for at most 10 test cases.

For the remaining cases, 1 ≤ ​N​ ≤ 1000.


Problem

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 ​V​i​. 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 = 10​8​ operations
Each test case begins with a line containing the integer ​N​. The second line 20 sec = 2x10​9​ 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

Time limit: 20 seconds per test set.


Time complexity for this operation: O(n)
Memory limit: 1GB. Overall Time Complexity: O(n​2​)

1 ≤ ​T​ ≤ 100.

0 ≤ ​V​i​ ≤ 2 × 10​5​.

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.

Note: Number of subarrays of an array with n elements = ​n​C​2​ + n = n*(n+1) / 2.

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.

Note: ​Number of subsequences of an array with n elements = 2​n​.

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:

Given Array: [0, -9, 1, 3, -4, 5]


Arrays Challenge-First Repeating Element 2. Keep updating idx[], while traversing the given array.

(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 <= 10​6
0 <= Ai <= 10​6

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 <= 10​5
0 <= Ai <= 10​10

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(n​2​)

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(N​2​)
Idea: For each subarray arr[i..j], calculate its sum. Space Complexity: O(N)
Time Complexity: O(N​3​)
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

Spiral order is given by:


1 5 7 9 10 11 21 41 70 105 95 81 79 70 40 15 9 6 10 12 13 20 32 68 63 59 55
25 29 30 29.

Algorithm: (We are given 2D matrix of n X m ).


1. We will need 4 variables:
a. row_start - ​initialized with 0.
b. row_end - ​initialized with n-1.
c. column_start - ​initialized with 0.
2D Array Challenges i.e. swap half of the elements of the diagonally upper half of the matrix with
the diagonally lower half once. In this, each (row, col) & (col, row) pair will
Challenge 1​ - Matrix Transpose be swapped exactly once and the transpose of the square matrix could be
obtained.
Problem
Given a square matrix A & its number of rows (or columns) N, return the
Code
transpose of A.
The transpose of a matrix is the matrix flipped over it's main diagonal, #include​<iostream>
switching the row and column indices of the matrix. using​ ​namespace​ ​std​;

int​ m​ ain​() {
Constraints ​int​ N = ​3;​
1 <= N <= 1000 ​int​ ​A​[N][N] = {{​1​, ​2​, ​3​}, {​4​, ​5​, ​6​}, {​7​, ​8​, ​9​}};

​for​(​int​ i=​0​; i<N; i++) {


Sample Input1
​for​(​int​ j=i; j<N; j++) {
A=[ //swap
[1,2,3], ​int​ temp = ​A​[i][j];
​A​[i][j] = ​A​[j][i];
[4,5,6],
​A​[j][i] = temp;
[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(N​2​)
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

Sample test case


Input

Second Iteration

3X4 4X3

Output
Third Iteration Sixth Iteration

Fourth Iteration Seventh 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​;
}

​for​(​int​ i​=​0​; i​<​n1; i​++​) {


​for​(​int​ j​=​0​; j​<​n3; j​++​)
{
​for​(​int​ k​=​0​; k​<​n2; k​++​) {
​ans​[i][j] ​+=​ ​m1​[i][k]​*​m2​[k][j];
}
}
}

​for​(​int​ i​=​0​; i​<​n1; i​++​) {


​for​(​int​ j​=​0​; j​<​n3; j​++​)
cout ​<<​ ​ans​[i][j] ​<<​" "​;
​ <​ endl;
cout <
}
}

Time Complexity: O(n1*n2*n3)


Challenge 3​ - 2D matrix Search Brute Force Approach
Linear search in a 2D Array.
Problem Code:
Given a nxm matrix. #include​ ​"bits/stdc++.h"
using​ ​namespace​ ​std​;
Write an algorithm to find that the given value exists in the matrix or not.
Integers in each row are sorted in ascending from left to right. int32_t​ ​main​() {
Integers in each column are sorted in ascending from top to bottom. ​int​ n, m; cin >> n >> m;
​int​ target; cin >> target;
​int​ ​mat​[n][m];
Constraints ​for​ (​int​ i = 0 ​ ​; i < n; i++) {
1 <= N,M <= 1,000 ​for​ (​int​ j = ​0​; j < m; j++) {
cin >> ​mat​[i][j];
}
Sample Test Case: }
Consider the following matrix: ​bool​ found = ​false​;
​for​ (​int​ i = 0
​ ​; i < n; i++) {
[
​for​ (​int​ j = ​0​; j < m; j++) {
[1, 4, 7, 11, 15], ​if​ (​mat​[i][j] == target)
[2, 5, 8, 12, 19], found = ​true​;
[3, 6, 9, 16, 22], }
}
[10, 13, 14, 17, 24], ​if​ (found)
[18, 21, 23, 26, 30] cout << ​"Found"​;
] ​else
cout << ​"Not Found"​;
Given target = 5, ​return true.
}

Given target = 20, ​return false. Time complexity : ​O(N*M)


Optimised Approach [IMP]
1. Start from the top right element.
2. You are at (r,c)
if(matrix[r][c] == target)
return true
If (matrix[r][c] > target)
c--
else
r++;
At (r,c), you can go to (r-1,c) or (r,c-1), depending on the value of matrix[i][j]
and target.
#include​ ​"bits/stdc++.h"
using​ ​namespace​ ​std​;
int32_t​ ​main​() {
​int​ ​n​, ​m​; cin >> ​n​ >> ​m​;
​int​ ​target​; cin >> ​target​;
​int​ ​mat​[​n​][​m​];
​for​ (​int​ ​i​ = 0
​ ​; ​i​ < n​ ​; ​i​++) {
​for​ (​int​ j​ ​ = ​0​; j​ ​ < ​m​; ​j​++) {
cin >> ​mat​[​i​][​j​];
}
}
​bool​ ​found​ = ​false​;
​int​ ​r​ = ​0​, ​c​ = ​n​ - ​1​;
​while​ (​r​ < ​m​ && ​c​ >= ​0​) {
​if​ (​mat​[​r​][​c​] == t
​ arget​) {
​found​ = ​true​;
}
​mat​[​r​][​c​] > ​target​ ? ​c​-- : ​r​++;
}
​if​ (​found​)
cout << ​"Found"​;
​else
cout << ​"Not Found"​;
}

Time complexity : ​O(N + M)


Important Questions
Char Arrays
Arrays of characters is known as Character Arrays.
1. Check if a given character array is a palindrome or not.
Palindrome: Given a string s, on reversing the string we get the same string we
Declaration
call that string is a palindrome.
To declare a character array of n size, we do
char arr[n+1];
For example:

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 i​th​ 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.

Getting started with the Pointers


Every variable is stored in the memory and each memory location has its own *(arr + i) is equivalent to arr[i].
memory address. It enables us to pass variables by reference. (arr + i) is the address of the ith element of the 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

In the above example, Supplementary material:


1. We declared an integer variable ‘a’, and an integer pointer ‘aptr’. Output-based questions/ MCQs.
2. The address of ‘a’ (&a) is stored in aptr.
3. cout << *aptr; gives the value stored at the memory address.
4. *aptr = 20 changes the value at the memory address to 20. Value of ‘a’ gets
changed to 20.
Dynamic Memory Allocation

Stack Memory Allocation


The memory is allocated on the function call stack. The memory gets deallocated
as soon as the function call gets over. Deallocation is handled by the compiler.

Heap Memory Allocation


Allocation takes place on the pile of memory space available to programmers to
allocated and de-allocate. The programmer has to handle the deallocation.
NOTE: ​It is different from the heap data structure.

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

Base idea: ‘a’ - ‘A’ = 32


1. Lowercase to UpperCase
Approach
1. Iterate over the string s and if s[i] is a lower case character, then update
s[i] -= 32

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 i​th​ character to the answer string.
2. s[i] != s[i-1] - then push_back the i​th​ character to the answer string.

Code
Bit Manipulation - I Toggle i​th​ bit
Mask: 1 << i
Prerequisites: ​knowledge of binary number system Bitwise XOR operation between n and mask toggle the i​th​ bit.

Get i​th​ bit:


Mask: Right shift n ‘i’ times, and check the first bit.

Update i’th bit to the given value


Mask: mask has all the bits set to one except i​th​ bit.
n = n & mask, i​th​ bit is cleared.
Now, to set i​th​ bit to value, we take value << pos as the mask.
Set i​th​ bit:
Mask: 1 << i
Bitwise OR operation between n and mask sets the i​th​ bit to one.

Clear i​th​ bit


Mask: ~ (1 << i )
In the mask, all the bits would be one, except the i​th​ bit. Taking bitwise AND with n
would clear the i​th​ bit.
Supplementary material Number of trailing zeroes:​ builtin_ctz(x)
Number of 1-bits:​ __builtin_popcount(x)
Compute XOR from 1 to n (direct method) :
int​ ​computeXOR​(​int​ n) Convert binary numbers directly into a decimal integer in C++.
{ #i​nclude​ ​<iostream>
​if​ (n % ​4​ == ​0​) using​ ​namespace​ ​std​;
​return​ n; ​int​ ​main​()
​if​ (n % ​4​ == ​1​) {
​return​ ​1​; ​int​ number ​=​ ​0b011​;
​if​ (n % ​4​ == ​2​) cout ​<<​ number;
​return​ n + ​1​; ​return​ ​0​;
​else }
​return​ ​0​;
}
Output: 3

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 = 2​x 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.

int​ ​setBitNumber​(​int​ ​n​)


{
n ​|=​ n​>>​1​;

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 j​th​ bit is set, then we take the j​th​ element.
Prerequisites: ​knowledge of binary number system There are a total of 2​n ​subsets.

Count set bits


n & (n - 1) sets the first set-bit to zero.
Explanation: n = XXX100
n - 1 = XXX011
n & ( n - 1 ) = XXX000

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 2​n ​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 i​th
​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​;

bool​ g​ etBit​(​int​ ​n​, ​int​ p


​ os​) {
​return​ ((​n​ & (​1​ << p ​ os​)) != ​0​);
}
int​ ​setBit​( ​int​ n​ ​, ​int​ ​pos​) {
​return​ (​n​ | (​1​ << ​pos​));
}
int​ ​unique​(​int​ ​arr​[], ​int​ ​n​) {
​int​ r​ esult​ = ​0​;
​for​ (​int​ ​i​ = 0
​ ​; ​i​ < ​64​; ​i​++) {
​int​ s​ um​ = ​0​;
​for​ (​int​ ​j​ = ​0​; ​j​ < ​n​; j
​ ​++) {
​if​ (​getBit​(​arr​[​j​], i ​ ​)) {
​sum​++;
}
}
​if​ (​sum​ % ​3​ != ​0​) {
​result​ = ​setBit​(​result​, ​i​);
}
}
​return​ r
​ esult​;
}
int​ ​main​() {
​int​ ​arr​[] = {​1​, ​2​, ​3​, ​4​, ​1​, ​2​, ​3​, ​1​, ​2​, ​3​};
​cout​ ​<<​ ​unique​(​arr​, ​10​) ​<<​ ​endl​;
​return​ ​0​;
}
Sieve of Eratosthenes
Sieve of Eratosthenes
Algorithm: We start from 2, and on each encounter of a prime number, we mark
its multiples as composite.
Finding primes in Range [1:n] without using Sieve of Eratosthenes
Time Complexity: O(n log log n)
We can check if each number is a prime or not. To check if the number ‘i’ is prime
Space Complexity: O(n)
we will traverse all the numbers till [2, sqrt(i)] can check if they divide n or not.
Similarly, we do this for all the n numbers.
Time Complexity: O(n sqrt n)
Space Complexity: O(1)
Prime Factorization using Sieve
Explanation:
while( num ! = 1 ):
We keep on dividing it with its smallest prime factor.
The smallest prime factor is pre-calculated using a slightly modified prime sieve.
Since we start from 2 and go on, we mark the first multiple as the spf.
Preprocessing for Sieve: O(n log log n)
Time Complexity for factorization: O(log n)
Space Complexity: O(n)

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​;

Approach int​ ​gcd​(​int​ ​a​, ​int​ ​b​){


We calculate the number of numbers divisible by a and b separately and then
subtract the number of numbers which are divisible by both a and b. ​while​(b​!=​0​){
​int​ rem​=​a​%​b;
a​=​b;
Code b​=​rem;
#include​<iostream> }
using​ ​namespace​ ​std​;
​return​ a;
}
int​ ​divisible​(​int​ ​n​, ​int​ ​a​, ​int​ ​b​){

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 n​p​ 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]

Objective: Check if the array is in strictly increasing order or not.


Time Complexity: O(N)
Space Complexity: O(N) for function call stack

bool​ s​ orted​(​int​ ​arr​[], ​int​ ​n​) {


​if​ (​n​ == ​1​) {
​return​ ​true​;
}
​bool​ ​restArray​ = ​sorted​(​arr​ + ​1​, ​n​ - ​1​);
​return​ (​arr​[​0​] < ​arr​[​1​] && ​restArray​);

You might also like