0% found this document useful (0 votes)
26 views45 pages

3

The document outlines a course on Data Structures and Algorithms (DSA) focusing on problem-solving skills across various coding platforms, targeting freshers and experienced candidates for interviews at top tech companies. It includes a detailed syllabus covering essential data structures, algorithms, and complexity analysis, along with the teaching methodology and course fees. The document also highlights the selection process for candidates based on their experience level and emphasizes the importance of implementation and problem-solving in interviews.

Uploaded by

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

3

The document outlines a course on Data Structures and Algorithms (DSA) focusing on problem-solving skills across various coding platforms, targeting freshers and experienced candidates for interviews at top tech companies. It includes a detailed syllabus covering essential data structures, algorithms, and complexity analysis, along with the teaching methodology and course fees. The document also highlights the selection process for candidates based on their experience level and emphasizes the importance of implementation and problem-solving in interviews.

Uploaded by

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

Data Structures and Algorithms

DSA you can say Mainly deals with problem solving :

stress more on solving programs across platforms like


Hackerrank , Leetcode , coding ninjas , GFG

Minimum 200 to 250 programs across all the coding platforms

Maang companies and top product based companies

Professors mainly stress about implementation part

How to solves problems

How to implement Linked List , Tree , Graph , Sorting and Searching algorithms

Lets assume interview time is 1 hr

15 to 20 mins : problems statemnets


===========================================

Top product based companies :


===========================

Microsoft , Amazon , Netflix ,Google

Ecommerce : Amazon , Flipkart , Ajio, Walmart , Mynthra

Payment related companies : Paypal , Phone pe , Razorpay, Cred pay

Health Care : medibuddy , United Health Group (Optum) , GE Health care

Banking companies : DBS bank, Lloyds Bank , Citi Bank , Standard Charted , Common
Welath Bank Australia (CBA)
================================

Selection process with experience Level :

A candiatate is a fresher or less than 2 years of experience

Fresher : He Need DSA round and domain Knowledge

Experience below 2 years :

DSA round + Domain Knowledge + LLD ( Low level design)

Experience of 4 years and above :

DSA + LLD +HLD + Domain Knowledge


==================================
My Way of Teaching :
=====================

I will be Stressing more on problem solving


across the platforms like Hackerrank , Leetcode , coding ninjas, GFG
I will be question link in chat box 5 mins for every
===============================================
Syllabus for DSA :
======================
1. Introduction :
Importance of DSA and Problem Solving
Complexity Analysis (Time and Space)

2. Basic Data structures


Arrays and Strings

3. Linked Lists
Singly Linked List
Doubly Linked List
Circular Linked List

4. Stacks and Queues

5. Hashing

6. Tress
Binary Tree
Binary Search Tree
Avl trees
Heap
Trie

7. Graph Algorithms

8. Sorting Algorithms
9. Searching Algorithms
10. Dynamic Programming
11. Greedy Algorithm
12. back tracking and Recursion, Divide and Conquer
13. Bit manipulation algorithm

========================================
Course Fee :
=============

8k with out recordings


10k with recordings for 1 year Validity
Daily i will provide notes in the portal
============================================
Arrays and Strings

if , if-else, for , while , nested for ,


Standard
===================================
Interview questions :
=====================
s.split("[ !,?._'@]+");
=====================================
/******************************************************************************

Online Java Compiler.


Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.

*******************************************************************************/
import java.util.*;
public class Main
{
public static void main(String[] args) {
String str1="anagramp";
//aagmnr
String str2="marganaq";
//aagmnr
char arr1[]=str1.toCharArray();
char arr2[]=str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);

String s1="";
String s2="";

for(int i=0;i<arr1.length;i++){
s1=s1+arr1[i];
}

for(int i=0;i<arr2.length;i++){
s2=s2+arr2[i];
}

System.out.println(s1);
System.out.println(s2);
if(s1.equals(s2)){
System.out.println("Both are Anagrams");
}else{
System.out.println("Not Anagrams");
}

}
}
===================================================
import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);


String A=sc.next();
String S="";
// for(int i=A.length()-1;i>=0;i--){
// S=S+A.charAt(i);
// }
// if(A.equals(S)){
// System.out.println("Yes");
// }else{
// System.out.println("No");
// }
String rev=new StringBuffer(A).reverse().toString();
if(A.equals(rev)){
System.out.println("Yes");
}else{
System.out.println("No");
}
/* Enter your code here. Print output to STDOUT. */

}
}
===========================================================

public static void main(String[] args) {


// TODO Auto-generated method stub

ArrayList<Integer> al=new ArrayList<>();


al.add(20);
al.add(45);
al.add(45);
al.add(50);
al.add(11);

Collections.sort(al);
System.out.println(al);

}
}
====================================================================

================================================================
int i=0;
int j=A.length()-1;
boolean flag=false;
while(i<j){
Character ch1=A.charAt(i);
Character ch2=A.charAt(j);
if(ch1!=ch2){
System.out.println("No");
flag=true;
break;
}
i++;
j--;

}
if(flag==false)
System.out.println("Yes");
/* Enter your code here.
========================================================

https://www.geeksforgeeks.org/problems/reverse-a-string/1
=======================================================
int min=Integer.MAX_VALUE:

for(int i=0;i<arr.length;i++)
{
if(arr[i]<min)
min=arr[i];
}
===========
HashSet properties are :

Duplicates not allowed


Insertion order is not preserved

TreeSet Properties are :


Duplicates are not allowed
They will arrange in Ascending order

package test;

import java.util.*;
public class Checker {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
HashSet<Integer> hs=new HashSet<>();
hs.add(10);
hs.add(20);
hs.add(20);
hs.add(30);

System.out.println(hs);

}
}

==========================================
Scanner scan=new Scanner(System.in);
TreeSet<Integer> hs=new TreeSet<>();
hs.add(10);
hs.add(20);
hs.add(20);
hs.add(30);

System.out.println(hs);
==================================================
LinkedHashSet<Integer> lhs=new LinkedHashSet<>();
Scanner scan=new Scanner(System.in);
LinkedHashSet<Integer> hs=new LinkedHashSet<>();
hs.add(10);
hs.add(30);
hs.add(20);
hs.add(0);

System.out.println(hs);
=================================================
LinkedHashMap<Integer,String> hm=new LinkedHashMap<>();
hm.put(10, "Shayali");
hm.put(20, "Vineeth");
hm.put(40, "Bhanuja");

String str=hm.get(40);
System.out.println(hm.containsKey(20));
System.out.println(str);

System.out.println(hm);
======================================================
Map Iterator :
=============
LinkedHashMap<Integer,String> hm=new LinkedHashMap<>();
hm.put(10, "Shayali");
hm.put(20, "Vineeth");
hm.put(40, "Bhanuja");

for(Map.Entry<Integer,String> me:hm.entrySet()) {
System.out.println(me.getKey()+" "+me.getValue());
}
========================================================

Data Structures and Algorithms :

Basic Programs :
==================
if-else
Functions & How to call functions
loops
Standard programs
Patterns
Arrays
Strings
======================
Write a program to print wheather a number is Even or Odd

Even numbers : 0, 2 , 4, 6, 8
Odd numbers : 1,3, 5, 7,9...

if a number is divisible by 2 then the number said to be Even else odd

% Modulus opearator it returns remainder

21%2==1 (odd if remainder and even if remainder 0)


22%2==0
23%2==1
===============================
Instead hard coding I want to take input from the end user and map them to our
local variables
===============================
package test;

import java.util.*;
public class Checker {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();

if(n%2==0) {
System.out.println("n is an even number");
}else {
System.out.println("n is an Odd number");
}

}
=======================================
2. Write a program to print n natural number

for(initialization ; conditioncheck;incr/decr){

}
1.initialization
2.condition check
3.statements
4.increment/decrement

2,3,4 steps will repet till your condition got failed


=================================================
import java.util.*;
public class Checker {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
System.out.println("Please enter the value of N");
int n=scan.nextInt();

System.out.println("The Values are");


for(int i=1;i<=n;i++) {
System.out.println(i);
}
//console : 1,2,3
//i=1 ; 1<=50
//i=2 2<=50
//i=3 3<=50

}
======================================================
3. Wap to print all the even numbers till n
we need to apply filter

if(i%2==0)
sop("print even number")
=======================================
import java.util.*;
public class Checker {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
System.out.println("Please enter the value of N");
int n=scan.nextInt();

System.out.println("The Values are");


for(int i=1;i<=n;i++) {
if(i%2==0) {
System.out.println(i);
}

}
//console : 1,2,3
//i=1 ; 1<=50
//i=2 2<=50
//i=3 3<=50

}
===============================================
3 Programs
================================================
Prime number I will explain in 3 ways by optimizing the iterations
4th Approach based on binary search

The number having 2 factors is called prime number


Those 2 factors are 1 and itself

will run a loop from 1 to <=n


will calculate count of all factors

if x is factor of n what is the basic requirement :


n%x==0

code :
for(int i=1;i<=n;i++) {
if(n%i==0) {
count=count+1;
}
}
if(count==2) {
System.out.println("It is a prime number");
}else {
System.out.println("It is not a prime number");
}
============================
n=5
i= 1 to 5

5%1==0 (crct) count=1


5%2!=0 count=1
5%3!=0 count=1
5%4!=0 count=1
5%5==0 count=2
=================================
n=1 lakh how many iterations loop is going
1 lakh
50k iterations

response time of Amazon has down by few milli seconds

number 2 to n/2

23/2 = 2 to 11

if you find a factor between 2 to n/2


count+=1
======================================
if(n<=1) {
System.out.println("It is not a prime
number");
}else {
for(int i=2;i<=n/2;i++) {
if(n%i==0) {
count=count+1;
break;
}
}
if(count==0) {
System.out.println("It is a prime number");
}else {
System.out.println("It is not a prime number");
}
}
=============================
if n=23
we will check from 2 to 23/2 = 11

if(count==0)
sop("It is a prime number")
================================
1 lakh to 50k

1 crore to 50 lakhs

2 to sqrt(100)
1 to 100
2 to 50
2 to 10
===========================
17 ==> 4

2 to 4

17%2!=0
17%3!=0
17%4!=0

if(count==0)
=======================
10000000
10000=10^7

Square root(some big number)= 1 lakh


=========================
Binary Search class
mid=1 + some big/2
mid*mid==number
==========================

Arrays , Strings , Map ,Stack , Queue , LL , Trees , GrapSorting algos ,


searching , Greedy , Dynamic programming , Recursion
2 pointer algos , sliding window algos
===============================

Nested for loop


Pattern problems
sum of a pair whose sum is equal to k
=============================================

What is time complexity :

Manish :
The Time taken by computer to execute the program is called time complexity

I wrote a program of length 500 lines

windows 8 gb i5 - 20 micro seconds


windows 16gb i7 - 10 micro seconds
Apple - 5 mili seconds
super computer - 1 milli second

Actual Defnition
the rate at which time increase wrt to inputs it is time complexity

0=dy/dx= dt/dinput =this rate is constant across all the machines

for(int i=0;i<n;i++)
{
system.out.println(x);
}
1. condition check
2. statement execution
3. incr/decr

5 -> 15+1= 16 steps == 0(16)=0(5*3+1) = 0(n*3+1)= 0(3n+1)~0(n)

computer scients measure time complexity in 3 ways


1 lakh + 1rupee ~ 1 lakh

big 0 notation
omega (X)
theata (X)
===================
distance - meters
liquid - liters
1 liter ~ 1 km
====================
ANSI - that measurement
======================
3 considerations for time complexity

1. always consider worst case time complexity


2. Avoid constants
3 . Avoid lower values

name=sc.next();
name= "Virat"
if(name == "Santosh")
sop("Hi I am Santosh"
else if(name == "Vineerth)
sop("Hi I am Vineeth"
else if(name == "Manish")
sop("Hi I am Manish")
else
sop("else user not found");

best time complexity is 0(2)


worst time complexity 0(8)

for(int i=0;i<n;i++)
{
sop("Hi I am Santosh");
}
=======================================
0(1) == Best Time complexity
for(int i=0;i<0;i++)
{
for(int i=0;i<0;i++)
{
}
}
==============================
I =0 time n
i=1 time n
i=2 timen

i=n time n

n+n+n+........................n
=n*n=0(n^2)
===================================

while()
{
}
is equivalent to for loop

i=0
while(i<n)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
}
}
i++;
}
==============================
it is order of 0(n^3)

n2 + n2 +.....

n*n^2=n^3=0(n^3)
========================================
Avg tc =best+worst/2

=======================

0(n^3+n+2) ~ 0(n^3)

0((1 lakh)^3 + 1 lakh +2) ~ 0(n^3)


============================

0(10^6+10000+2)

1 crore ~
0(1)
=============================
for(i=0;i<n;;i++)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{}
}
}

for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{}
}

o(n^3+n^2) = 0(n^3)
===================
for(i=0;i<n;i++)
{
}

for(int i=0;i<n;i++)
{
if else break continue
}
for(int i=0;i<n;i++)
{
if
}

0(n)+0(n)+0(n)= 3*0(n) = 0(n)

0(1),0(n), 0(n^2), 0(n^3)

0(log n) binary search


0(n logn) Merge sort , Quick sort

Nested for loop


Pattern problems
sum of a pair whose sum is equal to k
=============================================

What is time complexity :

Manish :
The Time taken by computer to execute the program is called time complexity

I wrote a program of length 500 lines

windows 8 gb i5 - 20 micro seconds


windows 16gb i7 - 10 micro seconds
Apple - 5 mili seconds
super computer - 1 milli second

Actual Defnition
the rate at which time increase wrt to inputs it is time complexity

0=dy/dx= dt/dinput =this rate is constant across all the machines

for(int i=0;i<n;i++)
{
system.out.println(x);
}
1. condition check
2. statement execution
3. incr/decr
5 -> 15+1= 16 steps == 0(16)=0(5*3+1) = 0(n*3+1)= 0(3n+1)~0(n)

computer scients measure time complexity in 3 ways

1 lakh + 1rupee ~ 1 lakh

big 0 notation
omega (X)
theata (X)
===================
distance - meters
liquid - liters
1 liter ~ 1 km
====================
ANSI - that measurement
======================
3 considerations for time complexity

1. always consider worst case time complexity


2. Avoid constants
3 . Avoid lower values

name=sc.next();
name= "Virat"
if(name == "Santosh")
sop("Hi I am Santosh"
else if(name == "Vineerth)
sop("Hi I am Vineeth"
else if(name == "Manish")
sop("Hi I am Manish")
else
sop("else user not found");

best time complexity is 0(2)


worst time complexity 0(8)

for(int i=0;i<n;i++)
{
sop("Hi I am Santosh");
}
=======================================
0(1) == Best Time complexity
for(int i=0;i<0;i++)
{
for(int i=0;i<0;i++)
{
}
}
==============================
I =0 time n
i=1 time n
i=2 timen

i=n time n

n+n+n+........................n
=n*n=0(n^2)
===================================
while()
{
}
is equivalent to for loop

i=0
while(i<n)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
}
}
i++;
}
==============================
it is order of 0(n^3)

n2 + n2 +.....

n*n^2=n^3=0(n^3)
========================================
Avg tc =best+worst/2

=======================

0(n^3+n+2) ~ 0(n^3)

0((1 lakh)^3 + 1 lakh +2) ~ 0(n^3)


============================

0(10^6+10000+2)

1 crore ~
0(1)
=============================
for(i=0;i<n;;i++)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{}
}
}

for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{}
}

o(n^3+n^2) = 0(n^3)
===================
for(i=0;i<n;i++)
{
}
for(int i=0;i<n;i++)
{
if else break continue
}

for(int i=0;i<n;i++)
{
if
}

0(n)+0(n)+0(n)= 3*0(n) = 0(n)

0(1),0(n), 0(n^2), 0(n^3)

0(log n) binary search


0(n logn) Merge sort , Quick sort

Nested for loop


Pattern problems
sum of a pair whose sum is equal to k
=============================================

What is time complexity :

Manish :
The Time taken by computer to execute the program is called time complexity

I wrote a program of length 500 lines

windows 8 gb i5 - 20 micro seconds


windows 16gb i7 - 10 micro seconds
Apple - 5 mili seconds
super computer - 1 milli second

Actual Defnition
the rate at which time increase wrt to inputs it is time complexity

0=dy/dx= dt/dinput =this rate is constant across all the machines

for(int i=0;i<n;i++)
{
system.out.println(x);
}
1. condition check
2. statement execution
3. incr/decr

5 -> 15+1= 16 steps == 0(16)=0(5*3+1) = 0(n*3+1)= 0(3n+1)~0(n)

computer scients measure time complexity in 3 ways

1 lakh + 1rupee ~ 1 lakh

big 0 notation
omega (X)
theata (X)
===================
distance - meters
liquid - liters
1 liter ~ 1 km
====================
ANSI - that measurement
======================
3 considerations for time complexity

1. always consider worst case time complexity


2. Avoid constants
3 . Avoid lower values

name=sc.next();
name= "Virat"
if(name == "Santosh")
sop("Hi I am Santosh"
else if(name == "Vineerth)
sop("Hi I am Vineeth"
else if(name == "Manish")
sop("Hi I am Manish")
else
sop("else user not found");

best time complexity is 0(2)


worst time complexity 0(8)

for(int i=0;i<n;i++)
{
sop("Hi I am Santosh");
}
=======================================
0(1) == Best Time complexity
for(int i=0;i<0;i++)
{
for(int i=0;i<0;i++)
{
}
}
==============================
I =0 time n
i=1 time n
i=2 timen

i=n time n
n+n+n+........................n
=n*n=0(n^2)
===================================

while()
{
}
is equivalent to for loop

i=0
while(i<n)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
}
}
i++;
}
==============================
it is order of 0(n^3)

n2 + n2 +.....

n*n^2=n^3=0(n^3)
========================================
Avg tc =best+worst/2

=======================

0(n^3+n+2) ~ 0(n^3)

0((1 lakh)^3 + 1 lakh +2) ~ 0(n^3)


============================

0(10^6+10000+2)

1 crore ~
0(1)
=============================
for(i=0;i<n;;i++)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{}
}
}

for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{}
}

o(n^3+n^2) = 0(n^3)
===================
for(i=0;i<n;i++)
{
}

for(int i=0;i<n;i++)
{
if else break continue
}

for(int i=0;i<n;i++)
{
if
}

0(n)+0(n)+0(n)= 3*0(n) = 0(n)

0(1),0(n), 0(n^2), 0(n^3)

0(log n) binary search


0(n logn) Merge sort , Quick sort

https://www.naukri.com/code360/problems/beautiful-string_1115625?
leftPanelTabValue=PROBLEM

https://www.hackerrank.com/challenges/java-loops/problem?isFullScreen=true

2
0 2 10
5 3 5

a=0 b=2 n=10

(0+1.2) (0+1.2+2.2) (0+1.2+2.2+4.2)

2 6

==========================================
class Solution{
public static void main(String []argh){
Scanner in = new Scanner(System.in);
int t=in.nextInt();
int a=0;
int b=0;
int n=0;
for(int k=0;k<t;k++){
a = in.nextInt();
b = in.nextInt();
n = in.nextInt();

int sum=0;
for(int i=0;i<n;i++){
sum=a;
for(int j=0;j<=i;j++){
sum=sum+(int)Math.pow(2,j)*b;
}
System.out.print(sum+" ");
}
System.out.println();

in.close();
}
}
================================================================
public class Solution {
public static int makeBeautiful(String str) {
int mincount=0;
int n=str.length();
String str1=generateString(0,str.length());
String str2=generateString(1,str.length());

int diff1=0;
int diff2=0;

for(int i=0;i<str.length();i++){
if(str.charAt(i)!=str1.charAt(i)){
diff1++;
}
}

for(int i=0;i<str.length();i++){
if(str.charAt(i)!=str2.charAt(i)){
diff2++;
}
}
return Math.min(diff1,diff2);
}
static String generateString(int control, int len){
String s="";
if(control==0){
for(int i=0;i<len;i++){
if(i%2==0){
s=s+'0';
}else{
s=s+'1';
}
}
}else{
for(int i=0;i<len;i++){
if(i%2==1){
s=s+'0';
}else{
s=s+'1';
}
}
}
return s;
}

}
====================================================================

1010
0101

0000 = 4

1010 = 2
0101 = 2

Math.min(2,2)=2

1010

1010 = 0
0101 = 4

Math.min(0,4)=0
============================================

001100

101010 =
010101
Arrays.sort(arr);
if(arr.length==1)
return 2;
int x=arr[arr.length-1];
int dummy[]=new int[x+1];
for(Integer z: arr){
dummy[z]=1;
}

int found=-1;
for(int i=1;i<=x;i++){
if(dummy[i]==0){
found= i;
}
}
if(found==-1)
return x+1;
else
return found;
https://www.geeksforgeeks.org/problems/find-duplicates-in-an-array/1
1 min

Vineet Kumar to You (direct message) 20:34


ok sir

=====================================================
//{ Driver Code Starts
import java.io.*;
import java.util.*;

class IntArray {
public static int[] input(BufferedReader br, int n) throws IOException {
String[] s = br.readLine().trim().split(" ");
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(s[i]);

return a;
}

public static void print(int[] a) {


for (int e : a) System.out.print(e + " ");
System.out.println();
}

public static void print(ArrayList<Integer> a) {


for (int e : a) System.out.print(e + " ");
System.out.println();
}
}

class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t;
t = Integer.parseInt(br.readLine());
while (t-- > 0) {

int n;
n = Integer.parseInt(br.readLine());

int[] arr = IntArray.input(br, n);

Solution obj = new Solution();


ArrayList<Integer> res = obj.duplicates(arr);

IntArray.print(res);
}
}
}

// } Driver Code Ends

https://www.geeksforgeeks.org/problems/find-duplicates-in-an-array/1
class Solution {
public static ArrayList<Integer> duplicates(int[] arr) {
// code here
//2 3 1
HashMap<Integer,Integer> hm=new HashMap<>();
//put , get , ContainsKey
//process each and every element
//check wheather the element present in Map or not
//if yes get actual freq+1
//if no just place aginest 1

for(Integer i: arr){
if(hm.containsKey(i)){
int actfreq=hm.get(i);
actfreq++;
hm.put(i,actfreq);
}else{
hm.put(i,1);
}
}
ArrayList<Integer> al=new ArrayList<>();
for(Map.Entry<Integer,Integer> me: hm.entrySet()){
if(me.getValue()>1){
al.add(me.getKey());
}
}
if(al.size()==0)
{
al.add(-1);
return al;
}
else{
Collections.sort(al);
return al;
}
}
}
===========================================================
https://www.geeksforgeeks.org/problems/find-the-frequency/1

//{ Driver Code Starts


//Initial Template for Java

import java.io.*;
import java.util.*;

class FastReader{
BufferedReader br;
StringTokenizer st;

public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}

String next(){
while (st == null || !st.hasMoreElements()){
try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){
e.printStackTrace(); }
}
return st.nextToken();
}

String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}

Integer nextInt(){
return Integer.parseInt(next());
}
}

class GFG {
public static void main(String args[]) throws IOException {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0) {
Solution ob = new Solution();
int N = sc.nextInt(), Arr[] = new int[N];
for(int i = 0;i<N;i++){
Arr[i] = sc.nextInt();
}

// element whose frequency to be find


int X = sc.nextInt();
out.println(ob.findFrequency(Arr, X));
}
out.flush();
}
}

// } Driver Code Ends

//User function Template for Java

class Solution{
int findFrequency(int arr[], int X){
HashMap<Integer,Integer> hm=new HashMap<>();
//put , get , ContainsKey
//process each and every element
//check wheather the element present in Map or not
//if yes get actual freq+1
//if no just place aginest 1

for(Integer i: arr){
if(hm.containsKey(i)){
int actfreq=hm.get(i);
actfreq++;
hm.put(i,actfreq);
}else{
hm.put(i,1);
}
}
int x=0;
for(Map.Entry<Integer,Integer> me: hm.entrySet()){
if(me.getKey()==X){
x= me.getValue();
}
}
return x;
}
}
=============================================
class Solution {
// Function to return the position of the first repeating element.
public static int firstRepeated(int[] arr) {
// Your code here
HashMap<Integer,Integer> hm=new HashMap<>();
int x=-1;
for(int i=arr.length-1;i>=0;i--){
if(hm.containsKey(arr[i])){
x=i+1;
}else{
hm.put(arr[i],1);
}
}
return x;
}
}

String req="";
for(int i=0;i<str.length();i++)
{
if(!req.conatins(str.charAt(i))
{
}
else{
}

================================

for(int i=0;i<str.length();i++)
{
for(int j=i+1;j<str.length();j++)
{
String sunstring = str.substring(i,j);
}
}
====================
n=5

i=0 5 combinat
0
0,1
0,1,2
0,1,2,3
0,1,2,3,4
============
i=1 4 combina

1
1,2
1,2

==================
n
n(n+1)/2 formula to calculate sum of n natural number

we need to check each combination of substring wheather it is unique or not


update maximum value based on situation
=============================
Sliding window 0(n)

class Solution {

public static int lengthOfLongestSubstring(String s) {


int max = 0;

for(int i=0;i<s.length();i++){
// apple 0,5
for(int j=i+1;j<=s.length();j++){
String subs=s.substring(i,j);//0,5
boolean check=hasUniqueCharacters(subs);
if(check==false){
if(subs.length()>max){
max=subs.length();
}
}
}
}
return max;

// return maxLength;
}

private static boolean hasUniqueCharacters(String substring) {

String req="";
for(int i=0;i<substring.length();i++){
if(!req.contains(substring.charAt(i)+"")){
req=req+substring.charAt(i)+"";
}else{
return true;
}
}
return false;

}
=============================================================

import java.awt.KeyEventDispatcher;
import java.util.*;

import com.sun.accessibility.internal.resources.accessibility;
//Longest s
public class Solution {

public static int kDistinctChars(int k, String str) {


// Write your code here
//aaaaaaaa= length of longest having one unique charactr
//
int max=0;
for(int i=0;i<str.length();i++)
{
for(int j=i+1;j<=str.length();j++){
String subs=str.substring(i,j);
int count= totaluniquechars(subs);
if(count<=k){
if(subs.length()>max){
max=subs.length();
}
}
}
}
return max;

}
static int totaluniquechars(String str){
String req="";
int count=0;
for(int i=0;i<str.length();i++){
if(!req.contains(str.charAt(i)+"")){
req=req+str.charAt(i);
}
}
return req.length();
}

}
===========================================================================

https://www.geeksforgeeks.org/problems/intersection-of-two-arrays2404/1?
utm_source=geeksforgeeks&utm_medium=ml_article_practice_tab&utm_campaign=article_pr
actice_tab

//{ Driver Code Starts


import java.io.*;
import java.util.*;

class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int t = Integer.parseInt(br.readLine().trim());
while (t-- > 0) {
// First array input
String[] str1 = br.readLine().trim().split(
" "); // Read the first line and split by spaces
int n = str1.length;
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(str1[i]); // Convert each element to an
integer
}

// Second array input


String[] str2 = br.readLine().trim().split(
" "); // Read the second line and split by spaces
int m = str2.length;
int[] b = new int[m];
for (int i = 0; i < m; i++) {
b[i] = Integer.parseInt(str2[i]); // Convert each element to an
integer
}

Solution sln = new Solution();


System.out.println(sln.numberofElementsInIntersection(a, b));
}
}
}
// } Driver Code Ends

class Solution {
public static int numberofElementsInIntersection(int a[], int b[]) {
// Your code here

HashSet<Integer> al=new HashSet<>();


for(Integer i:a){
al.add(i);
}
int count=0;
for(Integer i:b){
if(al.contains(i)){
count++;
}
}
return count;
}
}
=================================================================

int maxlen=0;
HashMap<Integer,Integer> hm=new HashMap<>();
int sum=0;
int n=arr.length;
for(int i=0;i<n;i++){
sum=sum+arr[i];
if(sum==k){
if(i+1>maxlen){
maxlen=i+1;
}
}
if(hm.containsKey(sum-k)){
int len=i-hm.get(sum-k);
if(len>maxlen){
maxlen=len;
}
}

if(!hm.containsKey(sum)){
hm.put(sum,i);
}
}
return maxlen;
========================================

k=4

1 2 1 0 1

sum=1
sum=1+2=3
sum= 3+1=4

int max=Integer.MIN_VALUE;
boolean found=false;
for(int i=0;i<arr.length;i++){
int sum=0;
for(int j=i;j<arr.length;j++){
sum=sum+arr[j];
if(sum==k){
found=true;
int cmax=j-i+1;
if(cmax>max){
max=cmax;
}

}
}
}
if(found==false)
return 0;
else
return max;
=============================================

Sliding Window :
==================
we need to make sure the window is Valid according to the
problem statement

2 types of window
window refers to Substring or SubArray

1. constant window

in a window of size we need no of Unique elements in each window

1, 2, 2 , 3,4,5

k=3

2. Variable size window

longest substring with out having duplicate characters


str =geeksforgeeks
eksforg
The size of the window will varying

we need to maintain 2 pointers


start pointer and end pointer

start=0;
end=0
getyueksforgeeks

tyue
max=end-start+1
HashMap is empty
end=2
start=0

t 1
y 1
u 1

will check e is there in the map or not

you need to maintain one hashmap

for(end=0;end<str.length();end++)
{
str.charAt(start)
}
we need to make sure content in the HashMap should be valid
between start and end pointer

first I will check wheather g is there in Map or not


Once you find your window is invalid
you need to start releasing characters from the map

m 1
n= 1

naman =
n
na
nam
nama X
naman X
----------
a
am
ama X
aman X
------------
m
ma
man
------------
a
an
-----
n
==============================

import java.util.*;

public class Solution


{

public static int countDistinctSubstrings(String str)


{
// Write your code here.
str=str.trim();
int start=0;
int end=0;
int sum=0;
HashMap<Character,Integer> hm=new HashMap<>();
for(end=0;end<str.length();end++){
Character ch=str.charAt(end);
while(hm.containsKey(ch)){
//you need to get every pointed by strat
//you need to remove same from the map
//geeksfor
Character c=str.charAt(start);
int x=hm.get(c);
x--;
hm.put(c,x);
if(hm.get(c)==0)
{
hm.remove(c);
}
start++;

}
hm.put(ch,1);
sum=sum+(end-start+1);
}
return sum+1;
}
}

Count of unique Substrings


Count of distinct substrings
Count of substrings having unique chars is different

Distinct Substrings
Definition: Distinct substrings are all the substrings of a string, counted without
regard to whether they contain repeated characters. Two substrings are considered
distinct if they differ in at least one character or their position in the string.
Example: For the string "aba":
Substrings: "", "a", "b", "a", "ab", "ba", "aba"
Distinct Substrings: "", "a", "b", "ab", "ba", "aba"
Total distinct substrings: 6

Unique Substrings
Definition: Unique substrings are those that appear only once in the string. If a
substring occurs multiple times, it is not counted as unique.
Example: For the string "aba":
Substrings: "", "a", "b", "a", "ab", "ba", "aba"
Unique Substrings: "", "b", "ab", "ba", "aba"
(The substring "a" is not unique because it appears twice.)
Total unique substrings: 5
Summary
Distinct Substrings: Count every unique instance of substrings, including those
that appear multiple times.
Unique Substrings: Only count substrings that appear exactly once in the original
string.
Exa
class Solution {
ArrayList<Integer> countDistinct(int k, int arr[]) {
// code here
ArrayList<Integer> al=new ArrayList<>();
for(int i=0;i<=arr.length-k;i++){
HashSet<Integer> hs=new HashSet<>();
for(int j=i;j<i+k;j++){
hs.add(arr[j]);
}
al.add(hs.size());
}
return al;
}
}
======================================================
[1, 2, 1, 3, 4, 2, 3]

strat=0
end=0

first i will count how many distinct elemnts are there each time i increment end
pointer

class Solution {
ArrayList<Integer> countDistinct(int k, int arr[]) {
// code here

int start=0;
int end=0;
HashMap<Integer,Integer> hm=new HashMap<>();
ArrayList<Integer> al=new ArrayList<>();
int dist=0;
int x=0;
for(int i=0;i<k;i++){
if(hm.containsKey(arr[i])){
x=hm.get(arr[i]);
x++;
hm.put(arr[i],x);
}else{
hm.put(arr[i],1);
dist++;
}
end++;
}
al.add(dist);
for(int i=k;i<arr.length;i++){
x=hm.get(arr[start]);
x--;
hm.put(arr[start],x);
if(hm.get(arr[start])==0){
hm.remove(arr[start]);
dist--;
}
start++;
//----------------
if(hm.containsKey(arr[i])){
x=hm.get(arr[i]);
x++;
hm.put(arr[i],x);
}else{
hm.put(arr[i],1);
dist++;
}

al.add(hm.size());

}
return al;
//O(k)+O(n)=0(k)
}
//0((n-k)*k)=O(n*k-k^2)=O(n*k)~0(n^2)
}
==============================================

//Search an elemnet in rotated sorted array

1. First we will calculate the mid element


2. Then check wheather arr[mid]>arr[start]
3. if above condition satisfied we can we find k is there or not
between arr[strat] and arr[mid]

3.then check for other part


=======================================================

if(arr[mid]>arr[mid+1])
return arr[mid+1]

if(arr[mid]<arr[mid-1])
return arr[mid]

=======================================
class Solution {
public int findMin(int[] arr) {
// complete the function here
int start=0;
int end=arr.length-1;

if(arr[start]<=arr[end]){
return arr[start];
}
while(start<=end){
int mid=start+(end-start)/2;
if(mid!=0 && arr[mid]<arr[mid-1]){ //26<12
return arr[mid];
}
if(mid!=arr.length-1 && arr[mid+1]<arr[mid]){//38<26
return arr[mid+1];
}

if(arr[mid]>arr[start]){
start=mid+1;
}else{
end=mid-1;
}
}
return -1;
}
}
static int firstPosition(int []arr, int x){
int start=0;
int end=arr.length-1;

int act=-1;
while(start<=end){
int mid=start+(end-start)/2;

if(arr[mid]==x){
act=mid;
end=mid-1;
}
else if(arr[mid]>x){
end=mid-1;
}else{
start=mid+1;
}
}
return act;
}

static int endPosition(int []arr, int x){


int start=0;
int end=arr.length-1;

int act=-1;
while(start<=end){
int mid=start+(end-start)/2;

if(arr[mid]==x){
act=mid;
start=mid+1;
}
else if(arr[mid]>x){
end=mid-1;
}else{
start=mid+1;
}
}
return act;
}

=============================================================================
https://www.naukri.com/code360/problems/first-and-last-position-of-an-element-in-
sorted-array_839724?interviewProblemRedirection=true&leftPanelTabValue=SUBMISSION

for(int i=0;i<n;i++)
{
sum=sum+arr[i];
}

0 1 2 3 4 5 7 8 9

arr[mid]==mid
every where my element value equal to Mid value;

Who so ever the part you got mismatch in that part only you can expect missing
element
==========================================================
class Solution {
public int missingNumber(int[] arr) {
Arrays.sort(arr);
int start=0;
int end=arr.length-1;

while(start<=end){
int mid=start+(end-start)/2;
if(arr[mid]==mid){
start=mid+1;
}else{
end=mid-1;
}
}

return start;
}
}
=========================================================
class Main {
public static void main(String[] args) {
System.out.println("Try programiz.pro");
int arr[]={1,2,3,5,6,9,-11,-12};
int max=Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++){
if(arr[i]>max){
max=arr[i];
}
}
System.out.println(max);
}
}
==========================================================
class Main {
public static void main(String[] args) {
System.out.println("Try programiz.pro");
int arr[]={1,2,3,5,6,9,9,9,-11,-12};
int fmax=Integer.MIN_VALUE;
int smax=Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++){
if(arr[i]>fmax){
smax=fmax;
fmax=arr[i];
}else if(arr[i]>smax && arr[i]!=fmax){
smax=arr[i];
}
}
System.out.println(smax);
}
}
=========================================================
Stack :
==========
Stack follows the principal of Last in First out

Shortened it will be called as LIFO (Last in First Out)


========================================================
Famous examples are

1. watsapp chat history


2. watsapp status history
3. In school days student note books
=======================================================
In technical way recusrsion follows stack
calling functions in a chain way follows stack principal

Now we need to replicate stack functionality :


===============================================
using array we need to replicate stack functionalitu

8.21 to 8.30

Push
pop
peek getting peek element
=================================
// Online Java Compiler
// Use this editor to write, compile and run your Java code online
import java.util.*;
class Main {
static int top =-1;
static int arr[]=new int[5];
public static void main(String[] args) {
System.out.println("Try programiz.pro");
while(true){
int opt=new Scanner(System.in).nextInt();
switch(opt){
case 1:
push(10);
break;
case 2:
pop();
break;
case 3:
display();
break;
}
}

}
static void push(int x){
top++;
arr[top]=x;
}
static int pop(){
int x= arr[top];
top--;
return x;
}
static void display(){
for(int i=top;i>=0;i--){
System.out.print(arr[i]+" ");
}
}

}
==========================================================
Queue:
===========

Queue follows principal first in first out

Can you give some practical examples of Queue

text messages
information will go in packets
Booked movie tickets at cinema Hall
==========================================================
Prcatical implemenation :
================================
1.Enque

2.Deque

3.display
================================

class Queue {
private int[] arr; // Array to store queue elements
private int front; // Index of the front element
private int rear; // Index of the last element
private int size; // Current size of the queue
private int capacity; // Maximum capacity of the queue

// Constructor to initialize the queue


public Queue(int capacity) {
this.capacity = capacity;
arr = new int[capacity];
front = -1;
rear = -1;
size = 0;
}

// Check if the queue is empty


public boolean isEmpty() {
return size == 0;
}

// Check if the queue is full


public boolean isFull() {
return size == capacity;
}

// Enqueue operation (add an element to the rear of the queue)


public void enqueue(int value) {
if (isFull()) {
System.out.println("Queue is full!");
return;
}

// If the queue is empty, set front to 0


if (front == -1) {
front = 0;
}

// Move rear to the next position (circular)


rear = (rear + 1) % capacity;
arr[rear] = value; // Add the new element to the rear
size++; // Increment the size of the queue
System.out.println("Enqueued: " + value);
}

//f=4 r=4
// 50

// Dequeue operation (remove an element from the front of the queue)


public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty!");
return -1; // Return a sentinel value for an empty queue
}

int dequeuedValue = arr[front];

// If there is only one element, reset the queue


if (front == rear) {
front = rear = -1;
} else {
// Move front to the next position (circular)
front = (front + 1) % capacity;
}

size--; // Decrement the size of the queue


return dequeuedValue;
}

// Display the elements of the queue


public void displayQueue() {
if (isEmpty()) {
System.out.println("Queue is empty!");
return;
}

System.out.print("Queue: ");
for (int i = 0; i < size; i++) {
// Print elements in the queue from front to rear (circular)
System.out.print(arr[(front + i) % capacity] + " ");
}
System.out.println();
}
}

public class QueueExample {


public static void main(String[] args) {
Queue queue = new Queue(5); // Create a queue with capacity 5

queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.displayQueue(); // Expected: 10 20 30

System.out.println("Dequeued: " + queue.dequeue()); // Expected: 10


queue.displayQueue(); // Expected: 20 30

queue.enqueue(40);
queue.enqueue(50);
queue.enqueue(60); // This will print "Queue is full!"
queue.displayQueue(); // Expected: 20 30 40 50
}
}
===================================================================================
==========

)[]{}

2. if you encountorere closing brace when the stack is empty the return false
1. When ever you encounter an opening brace push on to the Stack
2. When ever you encounter a closing brace what is peak element popout that
3. After processing whole string if your Stack is empty then String is Balanced

(]{}
===================================================================================
==========
//{ Driver Code Starts
//Initial Template for Java
import java.io.*;
import java.util.*;
class GFG{
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
int t = Integer.parseInt(sc.nextLine());
while(t-- > 0){
String S = sc.nextLine().trim();
Solution ob = new Solution();
if(ob.valid(S))
System.out.println(1);
else
System.out.println(0);

System.out.println("~");
}
}
}
// } Driver Code Ends

//User function Template for Java


class Solution
{
boolean valid(String str)
{
// code here
Stack<Character> s=new Stack<>();
for(int i=0;i<str.length();i++)
{
Character ch=str.charAt(i);
if(s.isEmpty() && (ch==')' || ch==']' || ch=='}'))
{
return false;
}
else if(ch==')' || ch==']' || ch=='}')
{

if(ch==')'){
if(s.peek()=='('){
s.pop();
}else{
return false;
}
}

if(ch==']'){
if(s.peek()=='['){
s.pop();
}else{
return false;
}
}

if(ch=='}')
{
if(s.peek()=='{')
{
s.pop();
}else{
return false;
}

}else{
s.push(ch);
}
}
if(s.isEmpty())
{
return true;
}
else
{
return false;
}

}
}

class Solution {
// Function to find the next greater element for each element of the array.
public ArrayList<Integer> nextLargerElement(int[] arr) {
// code here
ArrayList<Integer> al=new ArrayList<>();

for(int i=0;i<arr.length;i++){
boolean check=false;
for(int j=i+1;j<arr.length;j++){
if(arr[i]<arr[j]){
al.add(arr[j]);
check=true;
break;
}
}
if(check==false){
al.add(-1);
}
}
return al;

}
}
=========================================================================

while(!stack.isEmpty() && asteroid<0 && stack.peek()>0){

if(stack.peek()>Math.abs(asteroid)
{
break;
}
else if(Math.abs(asteroid)>stack.peek())
{
stack.pop();

}else{
stack.pop();
break;
}
}

if(stack.isEmpty() || asteroid>0 || stack.peek()>0)


stack.push(asteroid)
========================================================
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack=new Stack<>();
boolean found=false;
for(int i=0;i<asteroids.length;i++){
int x=asteroids[i];
found=false;
while(!stack.isEmpty() && x<0 && stack.peek()>0){
if(stack.peek()>Math.abs(x)){
break;
}else if(stack.peek()<Math.abs(x)){
stack.pop();
}else{
stack.pop();
found=true;
break;
}
}
if(found==false){
if(stack.isEmpty() || x>0 || stack.peek()<0){
stack.push(x);
}
}
}
int c=0;
int ans[]=new int[stack.size()];
for(Integer i:stack){
ans[c]=i;
c++;
}
return ans;
}
}
===============================================================

while(!stack.isEmpty() && asteroid<0 && stack.peek()>0){

if(stack.peek()>Math.abs(asteroid)
{
break;
}
else if(Math.abs(asteroid)>stack.peek())
{
stack.pop();

}else{
stack.pop();
break;
}

}
if(stack.isEmpty() || asteroid>0 || stack.peek()>0)
stack.push(asteroid)
========================================================
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack=new Stack<>();
boolean found=false;
for(int i=0;i<asteroids.length;i++){
int x=asteroids[i];
found=false;
while(!stack.isEmpty() && x<0 && stack.peek()>0){
if(stack.peek()>Math.abs(x)){
break;
}else if(stack.peek()<Math.abs(x)){
stack.pop();
}else{
stack.pop();
found=true;
break;
}
}
if(found==false){
if(stack.isEmpty() || x>0 || stack.peek()<0){
stack.push(x);
}
}
}
int c=0;
int ans[]=new int[stack.size()];
for(Integer i:stack){
ans[c]=i;
c++;
}
return ans;
}
}
===============================================================

https://www.geeksforgeeks.org/problems/circular-linked-list/1?
itm_source=geeksforgeeks&itm_medium=article&itm_campaign=practice_card
class Solution {
boolean isCircular(Node head) {
// Your code here
if(head.next==null){
if(head.next==head){
return true;
}else{
return false;
}
}
Node temp=head.next;

while( temp.next!=null){
if(temp==head)
return true;
temp=temp.next;
}
return false;
}
}
===========================================================

You might also like