3
3
How to implement Linked List , Tree , Graph , Sorting and Searching algorithms
Banking companies : DBS bank, Lloyds Bank , Citi Bank , Standard Charted , Common
Welath Bank Australia (CBA)
================================
3. Linked Lists
Singly Linked List
Doubly Linked List
Circular Linked List
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 :
=============
*******************************************************************************/
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.*;
}
}
===========================================================
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 :
package test;
import java.util.*;
public class Checker {
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());
}
========================================================
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...
import java.util.*;
public class Checker {
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
}
======================================================
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 {
}
//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
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
number 2 to n/2
23/2 = 2 to 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
Manish :
The Time taken by computer to execute the program is called time complexity
Actual Defnition
the rate at which time increase wrt to inputs it is time complexity
for(int i=0;i<n;i++)
{
system.out.println(x);
}
1. condition check
2. statement execution
3. incr/decr
big 0 notation
omega (X)
theata (X)
===================
distance - meters
liquid - liters
1 liter ~ 1 km
====================
ANSI - that measurement
======================
3 considerations for time complexity
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");
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(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
}
Manish :
The Time taken by computer to execute the program is called time complexity
Actual Defnition
the rate at which time increase wrt to inputs it is time complexity
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)
big 0 notation
omega (X)
theata (X)
===================
distance - meters
liquid - liters
1 liter ~ 1 km
====================
ANSI - that measurement
======================
3 considerations for time complexity
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");
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(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
}
Manish :
The Time taken by computer to execute the program is called time complexity
Actual Defnition
the rate at which time increase wrt to inputs it is time complexity
for(int i=0;i<n;i++)
{
system.out.println(x);
}
1. condition check
2. statement execution
3. incr/decr
big 0 notation
omega (X)
theata (X)
===================
distance - meters
liquid - liters
1 liter ~ 1 km
====================
ANSI - that measurement
======================
3 considerations for time complexity
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");
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(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
}
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
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
=====================================================
//{ 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;
}
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());
IntArray.print(res);
}
}
}
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
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();
}
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
class Solution {
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;
}
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 {
}
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
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
}
class Solution {
public static int numberofElementsInIntersection(int a[], int b[]) {
// Your code here
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
1, 2, 2 , 3,4,5
k=3
start=0;
end=0
getyueksforgeeks
tyue
max=end-start+1
HashMap is empty
end=2
start=0
t 1
y 1
u 1
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
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.*;
}
hm.put(ch,1);
sum=sum+(end-start+1);
}
return sum+1;
}
}
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)
}
==============================================
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;
}
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
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:
===========
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
//f=4 r=4
// 50
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();
}
}
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.displayQueue(); // Expected: 10 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
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;
}
}
=========================================================================
if(stack.peek()>Math.abs(asteroid)
{
break;
}
else if(Math.abs(asteroid)>stack.peek())
{
stack.pop();
}else{
stack.pop();
break;
}
}
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;
}
}
===========================================================