0% found this document useful (0 votes)
69 views

Coding Question

Uploaded by

nitinsr246
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Coding Question

Uploaded by

nitinsr246
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 121

LOve sir

A> Array.

1.Write a program to reverse an array or string?


Input : arr[] = {1, 2, 3}
Output : arr[] = {3, 2, 1}
code:-
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={1,2,3};
int i;
for(i=n.length-1;i>=0;i--)
{
System.out.println(n[i]);
}
}
}

2.Maximum and minimum of an array using minimum number of comparisons?


Input: arr[] = {3, 5, 4, 1, 9}
Output: Minimum element is: 1
Maximum element is: 9
in->O(n)
code:-
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={3,5,4,1,9};
int max=0,min=0;
int i;
for(i=0;i<n.length;i++)
{
max=n[0];
min=n[0];
}
for(i=0;i<n.length;i++)
{
if(n[i]>max)
{
max=n[i];
}
else if(n[i]<min)
{
min=n[i];
}
}
System.out.println("Min no is:"+min+"\n"+"Max no is:"+max);
}
}

OR

public static void main(String args[])


{
int n[]={3,4,4,2,1,5};
Arrays.sort(n);
int min=n[0];
int max=n[n.length-1];
}
3.Kth smallest element
Input:
N = 6
arr[] = 7 10 4 3 20 15
K = 3
Output : 7

code:-
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={7,10,4,3,20,15};
int i,j,temp=0,k=3;
for(i=0;i<n.length;i++)
{
for(j=0;j<n.length-1;j++)
{
if(n[j]<n[j+1])//sorting part
{
temp=n[j];
n[j]=n[j+1];
n[j+1]=temp;
}
}
}
for(i=0;i<n.length;i++)
{
System.out.println(n[k]);
break;
}
}
}

4.Sort an array of 0s, 1s and 2s without using shorting algo?


Input:
N = 5
arr[]= {0 2 1 2 0}
Output:
0 0 1 2 2
code:-
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={0,2,1,2,0};
int zero=0,one=0,two=0,i;
for(i=0;i<n.length;i++)
{
if(n[i]==0)
{
zero++;
}
if(n[i]==1)
{
one++;
}
if(n[i]==2)
{
two++;
}
}
for(i=0;i<zero;i++)
{
System.out.println(n[i]=0);
}
for(i=zero;i<one+zero;i++)
{
System.out.println(n[i]=1);
}
for(i=one+zero;i<n.length;i++)
{
System.out.println(n[i]=2);
}
}
}

5.Move all negative numbers to beginning and positive to end with constant extra
space?
Input: -12, 11, -13, -5, 6, -7, 5, -3, -6
Output: -12 -13 -5 -7 -3 -6 11 6 5
code:-
import java.util.*;
class ns
{
public static void main(String[] args) {
int n[]={-12,11,-13,-5,6,-7,5};
int l=0;
int r=n.length-1;
int temp=0;
while(l<r)
{
if(n[l]<0)
{
l++;
r--;
}
else if(n[l]>0 && n[r]<0)
{
temp=n[l];
n[l]=n[r];
n[r]=temp;
}
else if(n[l]<0 && n[r]<0)
{
l++;
}
else
{
r--;
}
}
for(int i=0;i<n.length;i++)
{
System.out.println(n[i]);
}
}
}

or

public void segregateElements(int arr[], int n)


{
// Your code goes here
ArrayList<Integer> al=new ArrayList<>();
for(int i=0;i<n;i++)
{
if(arr[i]>=0)
{
al.add(arr[i]);
}
}
for(int i=0;i<n;i++)
{
if(arr[i]<0)
{
al.add(arr[i]);
}
}
for(int i=0;i<n;i++)
{
arr[i]=al.get(i);
}
}

6.Union of two arrays


Input:
5 3
1 2 3 4 5
1 2 3
Output:
5
so basically we used Hashset for that
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={1,2,3,4,5};
int n1[]={1,2,3};
int a=n.length;
int b=n1.length;
int i,size=0;
HashSet<Integer> s=new HashSet<>();
for(i=0;i<a;i++)
{
s.add(n[i]);
}
for(i=0;i<b;i++)
{
s.add(n1[i]);
}
size=s.size();
System.out.println(size);
}
}

OR

public static ArrayList<Integer> findUnion(int arr1[], int arr2[], int n, int


m)
{
// add your code here

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


for(int i=0;i<n;i++)
hs.add(arr1[i]);
for(int i=0;i<m;i++)
hs.add(arr2[i]);
ArrayList<Integer> arr=new ArrayList<>(hs);
Collections.sort(arr);
return arr;
}

7.Sub array
code:
//sub array
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={1,2,3,4,5};
int i,j,k;
for(i=0;i<n.length;i++)
{
for(j=0;j<n.length;j++)
{
for(k=i;k<j;k++)
{
System.out.print(n[k]);
}
System.out.println();
}
}
}
}

8.SUM of subarray with time complexity of n^2 and return maximum sub array?
//sub array
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={5,4,-1,7,8};
int i,j,k,max=0;
for(i=0;i<n.length;i++)
{
int sum=0;
for(j=i;j<n.length;j++)
{
sum=sum+n[j];
if(sum>max)
{
max=sum;
}
}
System.out.print(sum);
System.out.println();
System.out.println(max);
}
}
}

9.Find the duplicate no


Input: nums = [1,3,4,2,2]
Output: 2
code:
class Solution {
public int findDuplicate(int[] nums) {
int i,j;
for(i=0;i<nums.length;i++)
{
for(j=i+1;j<nums.length;j++)
{
if(nums[i]==nums[j])
{
return nums[j];

}
}
}
return nums[j];
}
}
OR

Duplicate no in O(1).
code:
class Solution {
public int findDuplicate(int[] nums) {
HashSet <Integer> set = new HashSet<>();
for (int n : nums)
{
if (set.contains(n)){
return n;
}
set.add(n);
}
return -1;
}
}

10.Merge two sorted arrays?


Input: ar1[] = {1, 5, 9, 10, 15, 20}, ar2[] = {2, 3, 8, 13}
Output: ar1[] = {1, 2, 3, 5, 8, 9}, ar2[] = {10, 13, 15, 20}
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[]={1,2,3,4,5};
int n1[]={1,2,3};
int a=n.length;
int b=n1.length,c,i;
c=a+b;
int res[]=new int[c];
for(i=0;i<a;i++)
{
res[i]=n[i];
}
for(i=0;i<b;i++)
{
res[a+i]=n1[i];
}
for(i=0;i<c;i++)
{
System.out.println(res[i]);
}
}
}

or O(1) without extra space

public static void main(String []args){


int n[]={2,4,5};
int n1[]={3,6,7};
int temp=0;
int a=n.length;
int b=n1.length;
int i=a-1;
int j=0;
while(i>=0 && j<=b)
{
if(n[i]>=n1[j])
{
temp=n[i];
n[i]=n1[j];
n1[j]=temp;
i--;j++;
}
else
{
break;
}
}
Arrays.sort(n);
Arrays.sort(n1);
for(i=0;i<a;i++)
{
System.out.println(n[i]);
}
for(i=0;i<b;i++)
{
System.out.println(n1[i]);
}

11.Find triplets with zero sum


Input: n = 5, arr[] = {0, -1, 2, -3, 1}
Output: 1
Explanation: 0, -1 and 1 forms a triplet
with sum equal to 0.
code:
import java.util.*;
class ns
{
public static void main(String args[])
{

int n[]={0,-1,2,-3,1};
int i,j,k,sum=0;
for(i=0;i<n.length-2;i++)
{
for(j=i+1;j<n.length-1;j++)
{
for(k=j+1;k<n.length;k++)
{
if(n[i]+n[j]+n[k]==0)
System.out.println("true");
break;
}
}
}
}
}

O(n^2)me

code:
class Solution
{
public static boolean find3Numbers(int A[], int n, int X) {
Arrays.sort(A);
int i,j,k,sum=0;
for(i=0;i<n-1;i++)
{
j=i+1;
k=n-1;
while(j<k)
{
sum=A[i]+A[j]+A[k];
if(sum==X)
{
return true;
}
else if(sum<X)
{
j++;
}
else
{
k--;
}
}
}
return false;
}
}
12.Missing no with repeated no ?
Input: arr[] = {3, 1, 3}
Output: Missing = 2, Repeating = 3
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={1,3,3};
int i,sum=0,j;
int expected=n.length+1,mis=0;
int totalexpectd=expected*(expected+1)/2;
for(i=0;i<n.length;i++)
{
sum=sum+n[i];
}
mis=totalexpectd-sum;
System.out.println("missing no is"+mis);
//repeated no
for(i=0;i<n.length;i++)
{
for(j=i+1;j<n.length;j++)
{
if(n[j]==n[i])
{
System.out.println("repeated no is:"+n[j]);
}
}
}
}
}

13.Missing Number
code:
class Solution {
int missingNumber(int array[], int n) {
// Your Code Here
int expected=n*(n+1)/2;
int tot=0;
for(int i:array)
{
tot=tot+i;
}
return expected-tot;
}
}

14.Median of an two unshorted different size of an array


Input: n[]={1,3,2,4} n1[]={9,6,7,8,5]
output:median is:5
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={2,3,5,8};
int n1[]={10,12,14,16,18,20};
int a=n.length;
int a1=n1.length;
int c=a+a1;
int res[]=new int[c];
int i,j,temp=0,si=0,li=0,mid=0;
for(i=0;i<a;i++)
{
res[i]=n[i];
}
for(i=0;i<a1;i++)
{
res[a+i]=n1[i];
}
for(i=0;i<c;i++)
{
for(j=0;j<c-1;j++)
{
if(res[j]>res[j+1])
{
temp=res[j];
res[j]=res[j+1];
res[j+1]=temp;
}
}
}
for(i=0;i<c;i++)
{
si=res[0];
li=res[c-1];
mid=(si+li)/2;
//System.out.println(res[i]);
System.out.println("--------------------------");
System.out.println("mid array is:"+mid);
}
}
}

15.Count Inversions
Input: N = 5, arr[] = {2, 4, 1, 3, 5}
Output: 3
Explanation: The sequence 2, 4, 1, 3, 5
has three inversions (2, 1), (4, 1), (4, 3).

code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={10,10,10};
int i,count=0,j;
for(i=0;i<n.length-1;i++)
{
for(j=i+1;j<n.length;j++)
{
if(n[i]>n[j])
{
count++;
}
}
}
System.out.println(count);
}
}

16.Check if two arrays are equal or not?


Input: arr1[] = {1, 2, 5, 4, 0}, arr2[] = {2, 4, 5, 0, 1}
Output: Yes
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int a[]={1,2,5};
int b[]={2,4,15};
int i,j,temp=0;
for(i=0;i<a.length;i++)
{
for(j=0;j<a.length-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(i=0;i<b.length;i++)
{
for(j=0;j<b.length-1;j++)
{
if(b[j]>b[j+1])
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
}
}
for(i=0;i<3;i++)
{

if(a[i]==b[i])
{
System.out.println("1");
break;
}
else
{
System.out.println("0");
break;
}
}
}
}

17.Rotate a array by group?


Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8, 9], K = 3
Output: 3, 2, 1, 6, 5, 4, 9, 8, 7
code:
import java.util.*;
public class HelloWorld{

public static void main(String []args){


int n[]={1,2,3,4,5,6,7,8,9};
int slow=0,fast=0,i,k=3;
int c=k;
int s=n.length;
slow=0;
fast=s-1;
while(slow<fast)
{
for(i=k-1;i>=slow;i--)
{
System.out.println(n[i]);
}
slow=k;
k=k+c;
}
}
}

18.Count pairs with given sum//O(n^2)


Input:
N = 4, K = 6
arr[] = {1, 5, 7, 1}
Output: 2
Explanation:
arr[0] + arr[1] = 1 + 5 = 6
and arr[1] + arr[3] = 5 + 1 = 6.
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={1,1,1,1};
int i,sum=0,count=0,j,k=2;
for(i=0;i<n.length;i++)
{
for(j=i+1;j<n.length;j++)
{
if(n[i]+n[j]==k)
{
count++;
}
}
}
System.out.println(count);
}
}

or O(n)[using two pointer approach],space is O(1)


code:
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
int n[]={1,2,4,5,6,8,9};
int x=7;
int low=0;
int high=n.length-1;
while(low<high)
{
if(n[low]+n[high]==x)
{
System.out.println(n[low]+"\t"+n[high]);
System.out.println(" ");
low++;high--;
}
else if(n[low]+n[high]>x)
{
high--;
}
else
{
low++;
}
}
}
}

19.Common element
Input:
n1 = 6; A = {1, 5, 10, 20, 40, 80}
n2 = 5; B = {6, 7, 20, 80, 100}
n3 = 8; C = {3, 4, 15, 20, 30, 70, 80, 120}
Output: 20 80
code:
class Solution
{
ArrayList<Integer> commonElements(int A[], int B[], int C[], int n1, int n2,
int n3)
{
HashSet<Integer> common = new HashSet<>();
int i=0,j=0,k=0;
while(i<n1 && j<n2 && k<n3){
if(A[i] == B[j] && B[j] == C[k]){
common.add(A[i]);
i++;j++;k++;
}else if(A[i]<=B[j] && A[i]<=C[k]){
i++;
}else if(B[j]<=A[i] && B[j]<=C[k]){
j++;
}else{
k++;
}
}
ArrayList<Integer> res = new ArrayList<>(common);
Collections.sort(res);
return res;
}
}

20.Subarray with sum 0


Input:
5
4 2 -3 1 6

Output:
Yes

Explanation:
2, -3, 1 is the subarray
with sum 0.
code:
import java.util.*;
class ns
{
public static void main(String args[])
{

int n[]={4,2,0,1,6};
int i,j,k,sum=0;
for(i=0;i<n.length-2;i++)
{
for(j=i+1;j<n.length-1;j++)
{
for(k=j+1;k<n.length;k++)
{
if(n[i]+n[j]+n[k]==0||n[i]==0)
System.out.println("true");
break;
}
}
}
}
}

21.Factorials of large numbers


Input: N = 5
Output: 120
Explanation : 5! = 1*2*3*4*5 = 120
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int a=5;
int i,fact=1;
for(i=a;i>0;i--)
{
fact=fact*i;
}
System.out.println(fact);
}
}

22.Maximum Product Subarray


Input:
N = 5
Arr[] = {6, -3, -10, 0, 2}
Output: 180
Explanation: Subarray with maximum product
is [6, -3, -10] which gives product as 180.

code:
import java.util.*;
class ns
{
public static void main(String args[])
{

int n[]={6,-3,-10,0,2};
int i,j,k,max=0;
for(i=0;i<n.length-2;i++)
{
for(j=i+1;j<n.length-1;j++)
{
for(k=j+1;k<n.length;k++)
{
if(n[i]*n[j]*n[k]>max)
{
max=n[i]*n[j]*n[k];
}
}
}
}
System.out.println(max);
}
}

23.Pallendrom no(121->121)
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int n=121;
int s=0,c,r;
c=n;
while(n>0)
{
r=n%10;
s=(s*10)+r;
n=n/10;
}
if(c==s)
{
System.out.println("pallendrom");
}
else
{
System.out.println("not pallendrom");
}
}
}

24.Count the occurence of an no in the array


eg:arr[]={1,2,3,2,1,3,4};
1->2
2->2
3->2
4->1
code:
import java.util.Arrays;
class ns
{
public static void main(String args[])
{
int n[]={3,1,2,2,1,2,3,3};
countOccurence(n);
}
static void countOccurence(int n[])
{
Arrays.sort(n);
for(int i=0;i<n.length-1;i++)
{
int count=1;
for(int j=i+1;j<n.length;j++)
{
if(n[i]==n[j])
{
count++;
}
else
{
break;
}
}
if(count>=1)
{
System.out.println(n[i]+"->"+count);
i+=count-1;
}
}
}
}

25.Given Array of size n and a number k, find all elements that appear
more than n/k times.
Input: arr[] = {3, 1, 2, 2, 1, 2, 3, 3}, k = 4
Output: {2, 3}

code:
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
int n[]={1,2,3,4,1,1,1,1};
HashMap <Integer,Integer>map=new HashMap<>();
int a=n.length;
int i;
for(i=0;i<a;i++)
{
if(map.containsKey(n[i]))
{
map.put(n[i],map.get(n[i])+1);
}
else
{
map.put(n[i],1);
}
}
for(int ans:map.keySet())
{
if(map.get(ans)>a/k)
{
System.out.println(ans);
}
}
}
}

26.Triplet Sum in Array


n = 6, X = 13
arr[] = [1 4 45 6 10 8]
Output:
true
code:
import java.util.*;
class ns
{
public static void main(String args[])
{

int n[]={1,2,4,3,6};
int i,j,k,sum=0;
for(i=0;i<n.length-2;i++)
{
for(j=i+1;j<n.length-1;j++)
{
for(k=j+1;k<n.length;k++)
{
if(n[i]+n[j]+n[k]==10)
{
System.out.println("true");
}
}
}
}
}
}

27.Reverse the string?


code:
import java.nio.Buffer;
import java.util.*;
class ns
{
public static void main(String args[])
{
String s="Geeks";
StringBuffer sb=new StringBuffer(s);
sb.reverse();
System.out.println(sb);
}
}

28.Cyclically Rotate an array by one?


Input:
N = 5
A[] = {1, 2, 3, 4, 5}
Output:
5 1 2 3 4

code:
import java.util.*;
class ns
{
public static void main(String agrs[])
{
int n[]={1,2,3,4,5};
int n1=n[n.length-1];
int i;
for(i=n.length-1;i>0;i--)
{
n[i]=n[i-1];
}
n[0]=n1;
for(i=0;i<n.length;i++)
{
System.out.println(n[i]);
}
}
}
29. left rotated an arrya by 1?
input:1,2,3,4,5
output:2,3,4,5,1
code:
import java.util.*;
class ns
{
public static void main(String agrs[])
{
int n[]={1,2,3,4,5};
int n1=n[0];

int i;
for(i=0;i<n.length-1;i++)
{
n[i]=n[i+1];
}
n[n.length-1]=n1;
for(i=0;i<n.length;i++)
{
System.out.println(n[i]);
}
//System.out.println(n1);
}
}
30.Check If array is sorted or not?
input:1,2,3,4,5;
output:1
code:
public class Solution {
public static int isSorted(int n, int []a) {
// Write your code here.
int i;
for(i=0;i<n-1;i++)
{
if(a[i]<=a[i+1]&&a[i]>=a[i+1])
{
return 1;
}
else
{
return 0;
}
}
return 0;
}
}

31.Move all the zero at end?


input=1,2,0,0,2,3
output:1,2,2,3,0,0
code:
public class Solution {
public static int[] moveZeros(int n, int []a) {
// Write your code here.
int temp=0,i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]==0)
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
return a;
}
}
or
ArrayList<Integer>al=new ArrayList<>();
for(int i=0;i<n.length;i++)
{
if(n[i]!=0)
{
al.add(n[i]);
}
}
for(int i=0;i<n.length;i++)
{
if(n[i]==0)
{
al.add(n[i]);
}
}
for(int ans:al)
{
System.out.println(ans);
}

32.Remove an no from array


import java.util.*;
class ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[]=new int[10];
int i,j,index,key;
System.out.println("enter 10 no");
for(i=0;i<10;i++)
{
n[i]=input.nextInt();
}
System.out.println("enter a no you want to delete");
key=input.nextInt();
index=9;
for(i=0;i<index;i++)
{
if(n[i]==key)
{
for(j=i+1;j<=index;j++)//yaha basicalyy asa ho reha h ki hum element pe
i+1 element ko override ker rehe h.
n[j-1]=n[j];
i--;
index--;
}
}
for(i=0;i<=index;i++)
{
System.out.print(n[i]);
}
}
}

33.>two sum?
input:4,1,2,3,1
target:5
output:1//4+1=5
code:
public class Solution {
public static String read(int n, int []book, int target){
// Write your code here.
int i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(book[i]+book[j]==target)
{
return "YES";
}
}
}
return "NO";
}
}

34.Superior Element(an superior element is called a superior element if it is


greater than its right element and last
element is also a superior element.
input:1,2,3,2
output :2,3
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={1,2,2,1};
int i,c=n[n.length-1];
System.out.println(c);
for(i=0;i<n.length-1;i++)
{
if(n[i]>n[i+1])
{
//System.out.println(n[n.length]);
System.out.println(n[i]);
}
}
//System.out.println(c);
}
}

35>Display all the triplet element whose sum=0?


input : -1,-1,2,0,1
output :
-1 -1 2
-1 0 1
code:
import java.util.*;
class ns
{
public static void main(String agrs[])
{
int n[]={-1,-1,2,0,1};
int i,j,k,sum=0;
for(i=0;i<n.length-1;i++)
{
for(j=i+1;j<n.length-1;j++)
{
for(k=j+1;k<n.length;k++)
{
if(n[i]+n[j]+n[k]==0)
{
System.out.println(n[i]+" "+n[j]+" "+n[k]+"\
n");
}
}
}
}
}
}
36.>Max consecutive Ones

input:-1,1,0,1,1,1
output:3
code:
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int n=nums.length;
int i,count=0,max=0;
for(i=0;i<n;i++)
{
if(nums[i]==1)
{
count++;
}
else
{
count=0;
}
if(count>max)
{
max=count;
}
}
return max;
}
}

37.Count longest consecutive sequence?


Explanation: The longest consecutive elements sequence is [1, 2, 3, 4].
Therefore its length is 4.//But here if duplicate element occour then we have to
treate as that
element as single element(no both used).
Input: nums = [100,4,200,1,3,2]
Output: 4
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={0,3,7,2,5,8,4,6,0,1};
int i,j,temp=0,count=1;
for(i=0;i<n.length;i++)
{
for(j=0;j<n.length-1;j++)
{
if(n[j]>n[j+1])
{
temp=n[j];
n[j]=n[j+1];
n[j+1]=temp;
}
}
}
for(i=0;i<n.length;i++)
{

for(j=i+1;j<n.length;j++)
{
if(n[i]+1==n[j])
{
count++;
}
}
//System.out.println(n[i]);
}
//System.out.println(count);
}
}

38>count total Subarray Sum Equals K


Input: nums = [1,1,1], k = 2
Output: 2
code:
class Solution {
public int subarraySum(int[] nums, int k) {
int i,j,sum=0,count=0;
for(i=0;i<nums.length;i++)
{
for(j=i;j<nums.length;j++)
{
sum=sum+nums[j];
if(sum==k)
{
count++;
}
}
}
return count;
}
}

39>Convert a string into its corresponding binary no?


Input 15
output:1111
code:
class Ns
{
public static void main(String args[])
{
int n=15;int n1=32;
String a=Integer.toBinaryString(n1);
System.out.println(a);
}
}

40> Kadane's Algorithm


ye basicalyy largest sum contiguous subarray find kerne ke liye used hota h .in
O(N) me
code:
class solution
{
int maxSubArrray(int n[])
{
int sum=0;
int max=0;
for(int i=0;i<n.length;i++)
{
sum=sum+n[i];
max=Integer.max(max,sum);
if(sum<0)
{
sum=0;
}
}
return max;
}
}
41>Rearrange array such that even positioned are greater than odd
code:
public static void main(String[] args)
{
int n[]={1,2,2,1};
int a=n.length;
System.out.println(a);
Arrays.sort(n);
int ans[]=new int[a];
int p=0,q=a-1;
for(int i=0;i<a;i++)
{
if((i+1)%2==0)
{
ans[i]=n[q--];
}
else
{
ans[i]=n[p++];
}
}
for(int i=0;i<a;i++)
{
System.out.println(ans[i]);
}
}

or

public static void rearrange(int[] arr, int n)


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

// if index is even
if (i % 2 == 0) {
if (arr[i] < arr[i - 1]) {

// swap two elements


int temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
}
}

// if index is odd
else {
if (arr[i] > arr[i - 1]) {

// swap two elements


int temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
}
}
}

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


System.out.print(arr[i] + " ");
}
}

// Driver code
public static void main(String[] args)
{
int n = 5;
int arr[] = { 1, 3, 2, 2, 5 };
rearrange(arr, n);
}
}

42>Segregate even and odd numbers


Input: arr[] = {7, 2, 9, 4, 6, 1, 3, 8, 5}
Output: 2 4 6 8 7 9 1 3 5
code:
public static void main(String[] args)
{
int n[]={1, 3, 2, 4, 7, 6, 9, 10};
int i,j,temp=0;
for(i=0;i<n.length;i++)
{
for(j=0;j<n.length-1;j++)
{
if(n[j]%2!=0 && n[j+1]%2==0)
{
temp=n[j];
n[j]=n[j+1];
n[j+1]=temp;
}
}
}
for(i=0;i<n.length;i++)
{
System.out.print(n[i]);
}

}
43>Reverse a array by kth step?
input: nums={1,2,3,4,5,6,7}
k=3
output:{5,6,7,1,2,3,4}
->so iss question ko solve kerne ke kiye hum ye kerenge ki sbse phele array k
decending order me sort kerenge
->0 se leke ke tk ke element ko accending order me sort kerenge.
->them k+1 se last element ko sort kerenge accending order me.
code :
class solution
{
public void rotate(int [] nums,int k)
{
reverse(nums,0,nums.length-1);//0-->n original array ko sort kiye.
reverse(nums,0,k-1);// 0--->n ,0 se n ko sort kiye
reverse(nums,k,nums.length-1);// k--->n.length //rest bache array ko sort kiye
}
public vodi reverse(int []nums,int start,int end)
{
while(start<end)
{
int temp=nums[start];
nums[start]=nums[end];
nums[end]=temp;
start++;
end--;
}
}
}

44>Rearrange an array such that arr[i] = i


Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]//it data not equal then on that place
add -1.
code:
public static void main(String args[])
{
int n[]={-1, -1, 6, 1, 9, 3, 2, -1, 4, -1};
int i,j,temp=0;
for(i=0;i<n.length;i++)
{
for(j=0;j<n.length;j++)
{
if(n[j]==i)
{
temp=n[j];
n[j]=n[i];
n[i]=temp;
break;
}
}
}
for(i=0; i< n.length; i++)
{

// If not present
if (n[i]!= i)
{
n[i]=-1;
}
}
for(i=0;i<n.length;i++)
{
System.out.println(n[i]+" ");
}

45>Pscals triangle?
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
code:
class JavaApplication3 {
public static void main(String args[])
{
int i,j,k;
for( i=0;i<6;i++)
{
//for space
for( j=1;j<6-i;j++)
{
System.out.print(" ");
}
int number=1;
//printing a no
for( k=0;k<=i;k++)
{
System.out.print(number+" ");
number=number*(i-k)/(k+1);
}
System.out.println();
}
}
}

46>Display a union?
code:
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
int n[]={1,2,3,4,5};
int n1[]={4,5,6,7,8};
HashSet<Integer> hs = new HashSet<Integer>();
int i;
for(i=0;i<n.length;i++)
{
hs.add(n[i]);
}
for(i=0;i<n1.length;i++)
{
hs.add(n1[i]);
}
Iterator<Integer> a=hs.iterator();
while(a.hasNext())
{
System.out.println("\n");
System.out.println(a.next());
}
}
}
ARRAYLIST:
1>add a 5 no but only show only that no which is uniques means duplicate is not
allowed and sort it?
input:1,2,3,1,2
output:1,2,3
import java.util.*;
class ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int temp=0,i;
ArrayList<Integer>list=new ArrayList<>();
for(i=0;i<5;i++)
{
temp=input.nextInt();
if(!list.contains(temp))
{
list.add(temp);
}
}
Collections.sort(list);
System.out.println(list);
}
}

B> MATRIX

1.Enter 3*3 Matrix and display sum ?


input :-1,2,3,4,5,6,7,8,9
output:
45//1+2+3+4+5+6+7+8+9

code:
import java.util.*;
class ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[][]=new int[3][3];
int i,j,sum=0;
System.out.println("enter 3*3 matrix element");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
n[i][j]=input.nextInt();
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum=sum+n[i][j];
}
}
System.out.println(sum);
}
}

2.Enter 3*3 Matrix and display all the even no?


input:-1,2,3,4,5,6,7,8,9
output:
even no is:2
even no is:4
even no is:6
even no is:8

code:
import java.util.*;
class ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[][]=new int[3][3];
int i,j,sum=0;
System.out.println("enter 3*3 matrix element");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
n[i][j]=input.nextInt();
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(n[i][j]%2==0)
{
System.out.println("even no is:"+n[i][j]);
}
}
}
}
}

3.Enter 3*3 Matrix and display all the odd no?


input:-1,2,3,4,5,6,7,8,9
output:
odd no is:1
odd no is:3
odd no is:5
odd no is:7
odd no is:9

code:
import java.util.*;
class ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[][]=new int[3][3];
int i,j,sum=0;
System.out.println("enter 3*3 matrix element");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
n[i][j]=input.nextInt();
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(n[i][j]%2!=0)
{
System.out.println("Odd no is:"+n[i][j]);
}
}
}
}
}

4.Enter 3*3 matrix and display all the element of left digonal?
input:1,2,3,4,5,6,7,8,9
output:1,5,9
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[][]=new int[3][3];
int i,j;
System.out.println("enter 3*3 matrix element");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
n[i][j]=input.nextInt();
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
{
System.out.println(n[i][j]);
}
}
}

}
}

5.Enter 3*3 matrix and display all the element of right digonal?
input:1,2,3,4,5,6,7,8,9
output:3,5,7
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[][]=new int[3][3];
int i,j;
System.out.println("enter 3*3 matrix element");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
n[i][j]=input.nextInt();
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if((i+j)==2)
{
System.out.println(n[i][j]);
}
}
}

}
}

6. Enter a 3*3 matrix and perform sum of an left digonal ?


input :1,2,3,4,5,6,7,8,9
output:15//1+5+9
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[][]=new int[3][3];
int i,j,sum=0;
System.out.println("enter 3*3 matrix element");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
n[i][j]=input.nextInt();
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
{
sum=sum+n[i][j];
}
}
}
System.out.println(sum);
}
}

7.Enter an 3*3 matrix and perform sum of right digonal?


input:1,2,3,4,5,6,7,8,9
output:15//3+5+7

code:
import java.util.*;
class ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[][]=new int[3][3];
int i,j,sum=0;
System.out.println("enter 3*3 matrix element");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
n[i][j]=input.nextInt();
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if((i+j)==2)
{
sum=sum+n[i][j];
}
}
}
System.out.println(sum);
}
}

8>Spiral Traversing of an matrix?


Input:
r = 4, c = 4
matrix[][] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15,16}}
Output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
code:
class Solution
{
static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c)
{
ArrayList<Integer> al=new ArrayList<>();
int top = 0, left = 0, bottom = r - 1, right = c - 1;
while(top <= bottom && left <= right){

for(int i = left; i <= right; i++){


al.add(matrix[top][i]);
}
top++;

for(int i = top; i <= bottom; i++){


al.add(matrix[i][right]);
}
right--;

if(top <= bottom){


for(int i = right; i >= left; i--){
al.add(matrix[bottom][i]);
}
bottom--;
}

if(left <= right){


for(int i = bottom; i >= top; i--){
al.add(matrix[i][left]);
}
left++;
}
}
return al;
}
}

9>Search a 2D Matrix
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
code:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0)return false;
int n=matrix.length;
int m=matrix[0].length;
int lo=0;
int hi=(n*m)-1;
while(lo<=hi)
{
int mid=(lo+(hi-lo)/2);
if(matrix[mid/m][mid%m]==target)
{
return true;
}
if(matrix[mid/m][mid%m]<target)
{
lo=mid+1;
}
else
{
hi=mid-1;
}
}
return false;
}
}

10>Sorted matrix:-Isme basically hume ye kerna h ki hume ek matrix given hoga to


hume use sort kerna h aur matrix me hi store kerna h.
Input:
N=4
Mat=[[10,20,30,40],
[15,25,35,45]
[27,29,37,48]
[32,33,39,50]]
Output:
10 15 20 25
27 29 30 32
33 35 37 39
40 45 48 50
code:
class Solution {
int[][] sortedMatrix(int N, int Mat[][]) {
// code here
ArrayList<Integer> al=new ArrayList<>();
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
al.add(Mat[i][j]);
}
}
Collections.sort(al);

int h=0;//ye h mera sorted matrix element to target ker reha

for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
Mat[i][j]=al.get(h++);//matrix ko sort kerne ke bd line by line
usko store ker rehe h new matrix me.
}
}
return Mat;
}
};

11>Transpose of a matrix :-Basically iska matlab ye hota h ki hum matrix ke jo row


me deta h use change kerke column me badal dete h.
eg:
input :
10 20
30 40
output:
10 30
20 40
code:
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[][]=new int[2][2];
int i,j;
System.out.println("enter element in 2*2 matrix");
for(i=0;i<n.length;i++)
{
for(j=0;j<n.length;j++)
{
n[i][j]=input.nextInt();
}
}
for(i=0;i<n.length;i++)
{
for(j=0;j<n.length;j++)
{
System.out.print(n[j][i]);
}
System.out.print("\n");
}
}

12>Rotate a matrix by 90 degree in clockwise direction without using any extra


space.(pre requires transpose of matrix)
Input:
1 2 3
4 5 6
7 8 9
Output:
7 4 1
8 5 2
9 6 3

so ba basically isko solve kerne ke liye hum transpose of matrix ka used kerenge

after transpose of matrix:


1 4 7
2 5 8
3 6 9

and after reversing that matrix we get out 90 degree matrix:


7 4 1
8 5 2
9 6 3

code:
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[][]=new int[3][3];
int i,j;
int temp=0;
System.out.println("enter element in 3*3 matrix");
for(i=0;i<n.length;i++)
{
for(j=0;j<n.length;j++)
{
n[i][j]=input.nextInt();
}
}
//transpose of matrix
for(i=0;i<n.length;i++)
{
for(j=i;j<n.length;j++)
{
temp=n[i][j];
n[i][j]=n[j][i];
n[j][i]=temp;
}
}
// reverse column
for(i=0;i<n.length;i++)
{
for(j=0;j<n.length/2;j++)
{
temp=n[i][j];
n[i][j]=n[i][n.length-1-j];
n[i][n.length-1-j]=temp;
}
}
for(i=0;i<n.length;i++)//print the matrix
{
for(j=0;j<n.length;j++)
{
System.out.print(n[i][j]);
}
System.out.print("\n");
}
}
C>SEARCHING and SORTING
1>Linear Search
input:1,3,4,3,4,4,5
key=4
output:data found at :4,5,6 place
code:
//liner search
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={1,2,4,5,2,3,5,3};
int i,key=4;
for(i=0;i<n.length;i++)
{
if(n[i]==key)
{
System.out.println("data found at :"+(i+1));

}
}
}
}

2>Binary Search

code:
//binary search
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={1,2,3,4,5,6,7};
int si=0,mi=0,li=0,key=3;
int i;
for(i=0;i<n.length;i++)
{
si=0;
li=n.length-1;
mi=(si+li)/2;
}
while(si<=li)
{
if(mi==key)
{
System.out.println("data found at :"+mi+"location");
break;
}
else if(key>mi)
{
li=mi+1;
}
else if(key<mi)
{
li=mi-1;
}
mi=(si+li)/2;
}
if(si>li)
{
System.out.println("data not found");

}
}
}

3>Implement Lower Bound


input:-1,2,2,3
output:-0
explain index 0 is smaller index suxh that arr[0] is not less than x
code:public class Solution {
public static int lowerBound(int []arr, int n, int x) {
// Write your code here
int l = 0;

int r = n-1;

while(l<=r){

int mid = (int)(l+r)/2;

if(x>arr[mid]){

l = mid+1;

else{
r = mid-1;

return l;
}
}
4> Search Insert Position
input:-1,2,4,7
output:-3
code:
public class Solution {
public static int searchInsert(int [] arr, int m){
// Write your code here.
int i,si=0,li=0,mi=0;
for(i=0;i<arr.length;i++)
{
si=0;
li=arr.length-1;
}
while(si<=li)
{
mi=(si+li)/2;
if(arr[mi]==m)
{
return mi;
}
else if(m>arr[mi])
{
si=mi+1;
}
else
{
li=mi-1;
}
}
return si;

}
}
5>Last occurence in a sorted array
input:-3,4,13,13,13,20,40 ,target=13
output:4//As the target value is 13 , it appears for the first time at index number
4.
code:
import java.util.*;
class ns
{
public static int cal()
{
int arr[]={3,4,13,13,13,20,40};
int i,target=93,count=0;
for(i=0;i<arr.length;i++)
{
if(arr[i]==target)
{
count=i;
}
else
{
count=-1;
}

}
return count;
}
public static void main(String args[])
{
// ns obj=new ns();
//int c=obj.cal();
System.out.println(cal());
}
}
6>Find the non repeating element in an array
eg:1,1,2,2,4,5,5
output:4
//so for solving this type of problem we user xor bcz in xor if same 2 value
present then it become 0.
code:
import java.util.*;
class ns
{
public static void main(String args[])
{
int n[]={1,1,2,2,4,5,5};
int ans=n[0];
int i;
for(i=1;i<n.length;i++)
{
ans=ans ^ n[i];
}
System.out.println(ans);
}
}
7>Peak element in array
Peak element is defined as the element greater than both of its neighbors.
Formally, if ‘arr[i]’ is the peak element,
‘arr[i – 1]’ < ‘arr[i]’ and ‘arr[i + 1]’ < ‘arr[i]’.
code:
int peakElement(int arr[], int n)
{
// Your code here
int low = 0;
int high = n-1;

while(low<=high){
int mid = (low+high)/2;

if(
(mid==0 || arr[mid]>=arr[mid-1]) &&
(mid == n-1 || arr[mid]>=arr[mid+1])
){
return mid;
}
else if(arr[mid]<=arr[mid+1]){
low = mid+1;
}else{
high = mid-1;
}
}

return -1;
}

8>Find Target Indices After Sorting Array


input:1,2,5,2,3 target =2
output:-1,2
code: using array list
class Solution {
public List<Integer> targetIndices(int[] nums, int target) {
List<Integer> list = new ArrayList<>();
Arrays.sort(nums);
for(int i=0; i<nums.length; i++){
if(nums[i]==target){
list.add(i);
}
}
return list;
}
}
9>Maximum Count of Positive Integer and Negative Integer
Input: nums = [-2,-1,-1,1,2,3]
Output: 3
Explanation: There are 3 positive integers and 3 negative integers.
The maximum count among them is 3.
code:
class Solution {
public int maximumCount(int[] nums) {
int i,max1=0,max2=0;
for(i=0;i<nums.length;i++)
{
if(nums[i]>0)
{
max1++;
}
else if(nums[i]<0)
{
max2++;
}
}
if(max1>max2)
{
return max1;
}
else
{
return max2;
}
}
}
10>Two Sum II - Input Array Is Sorted
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1,
index2 = 2. We return [1, 2].
code:1
class Solution {
public int[] twoSum(int[] n, int target) {
int i = 0, j = n.length - 1;
while(i < j){
if(n[i] + n[j] == target){
return new int[]{i + 1, j + 1};
}else if(n[i] + n[j] > target){
j--;
}else{
i++;
}
}
return new int [] {-1,-1};
}
}
code 2:
package ns;
import java.util.*;
class Ns
{
public static void main(String args[])
{
int n[]={-1,0};
int i,target=-1,j;
for(i=0;i<n.length;i++)
{
for(j=i+1;j<n.length;j++)
{
if(n[i]+n[j]==target)
{
System.out.println((i+1)+"\n"+(j+1));
//return new int[]{i+1,j+1};
}
}
}
}
}
11>Check If N and Its Double Exist
Input: arr = [10,2,5,3]
Output: true
Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]
code:
class Solution {
public boolean checkIfExist(int[] arr) {
int i,j;
for(i=0;i<arr.length;i++)
{
for(j=0;j<arr.length;j++)
{
if(arr[i]==2*arr[j]&(i!=j))
{
return true;
}
}
}
return false;
}
}
12>Sqrt(x)
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round
it down to the nearest integer, 2 is returned.
code:
class Solution {
public int mySqrt(int x) {
double c=Math.sqrt(x);
int ans=(int)c;
return ans;
}
}
13>Valid Perfect Square
Input: num = 16
Output: true
Explanation: We return true because 4 * 4 = 16 and 4 is an integer.
code:
class Solution {
public boolean isPerfectSquare(int num) {
double c=Math.sqrt(num);
int ans=(int)c;
if(ans*ans==num)
{
return true;
}
return false;
}
}

14>First and last occurrences of x


n=9, x=5
arr[] = { 1, 3, 5, 5, 5, 5, 67, 123, 125 }
Output:
2 5
Explanation:
First occurrence of 5 is at index 2 and last occurrence of 5 is at index 5.

code:using arraylist

class GFG
{
ArrayList<Integer> find(int arr[], int n, int x)
{
// code here
ArrayList<Integer> l=new ArrayList<Integer>();
int i,j;
for(i=0;i<n;i++)
{
if(arr[i]==x)
{
l.add(i);
break;
}
}
for(j=n-1;j>=0;j--)
{
if(arr[j]==x)
{
l.add(j);
break;
}
}
if(l.isEmpty())
{
l.add(-1);
l.add(-1);
return l;
}
return l;
}
}

or by using array
package ns;
import java.util.*;
class Ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[]={1,3,5,5,5,5,67,123};
int i,j;
int t=5,c=0,c1=0;
for(i=0;i<n.length;i++)
{
if(n[i]==t)
{
c=i;
}
}
for(j=n.length-1;j>=0;j--)
{
if(n[j]==t)
{
c1=j;
}
}
System.out.println(c1);
System.out.println(c);
}
}

15>Value equal to index value


N = 5
Arr[] = {15, 2, 45, 12, 7}
Output: 2
Explanation: Only Arr[2] = 2 exists here.

By using array list


class Solution {
ArrayList<Integer> valueEqualToIndex(int arr[], int n) {
// code here
ArrayList<Integer> l=new ArrayList<Integer>();
int i;
for(i=0;i<n;i++)
{
if(arr[i]==i+1)
{
l.add(i+1);
}
}
return l;
}
}

By using simple code:


import java.util.*;
class Ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[]={15,2,45,12,7};
int n1[]=new int[5];
int i,j;
for(i=0;i<n.length;i++)
{
if(n[i]==i+1)
{
System.out.println(i+1);
}
}

}
}

16>Find Pair Given Difference


Input:
L = 6, N = 78
arr[] = {5, 20, 3, 2, 5, 80}
Output: 1
Explanation: (2, 80) have difference of 78.
code:
class Solution
{
public boolean findPair(int n[], int size, int n1)
{
//code here.
int i,j;
for(i=0;i<size;i++)
{
for(j=i+1;j<size;j++)
{
if(n[i]-n[j]==n1||n[j]-n[i]==n1)
{
return true;
}
}
}
return false;
}
}

17>BUBBLE SORT (isme basically swap hota h)


code:
code:
import java.util.*;
class Ns
{
public static void main(String args[])
{
int n[]={2,8,5,4};
int i,k,temp=0,j;
for(i=0;i<n.length;i++)
{
for(j=0;j<n.length-1;j++)
{
if(n[j]>n[j+1])
{
temp=n[j];
n[j]=n[j+1];
n[j+1]=temp;
}
}
}
for(i=0;i<n.length;i++)
{
System.out.println(n[i]);
}
}
}

18>Insertion Sort (Isme basicalyy shift hota h,isme data apne ek phele wale se
compare kerte h
aur logic ke hisab se shift ho jata h,(until end to front),just like tash ka patta
jis format me rehta h.

19> Middle of three


Input:A=978,B=518,C=300
Output:
518
Explanation:
since 518>300 and 518 <978,so 518 is the middle element.
code:
class Solution{
int middle(int A, int B, int C){
//code here
if(A>C &&A<B || A<C && A>B )
{
return A;
}
else if(B>C && B<A || B<C && B>A)
{
return B;
}
else
{
return C;
}
}
}

20>Count triplet with sum smaller than X in O n^2


input n=4,sum=2
arr[]={-2,0,1,3};
output =2
Explanation:Below are triplet with sum less than 2 (-2,0,1) and (-2,0,3)
code:
class Solution
{
long countTriplets(long arr[], int n,int sum)
{
int c =0;
Arrays.sort(arr);
for(int k=0;k<n-2;k++)
{
int i=k+1;
int j=n-1;
while(i<j)
{
long s=arr[k]+arr[i]+arr[j];
if(s<sum)
{
c+=(j-i);
i++;
}
else j--;
}
}
return c;
}
}

21>Product array puzzle:Given an array nums[] of size n, construct a Product array


p (of same size n) such that P[i]is
equal to product of all the elements of nums expected nums[i].
Input:
n=5
nums[]={10,3,5,6,2};
output:
180 600 360 900
Explanation:
For i=0 ,P[i]=3*5*6*2=180.
For i=1 ,P[i]=10*5*6*2=600.
For i=2 ,P[i]=10*3*6*2=360.
For i=3 ,P[i]=10*3*5*2=300.
For i=4 ,P[i]=10*3*5*6=900.
code:
class Ns
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n[]={10,3,5,6,2};
int v=n.length;
int i;
int n1[]=new int[v];
int c;
int anss[]=new int[v];
int mult=1;
for(i=0;i<n.length;i++)
{
mult=mult*n[i];
}
for(i=0;i<n.length;i++)
{
c=n[i];
anss[i]=mult/c;
System.out.println(anss[i]);
}
}
}

orr

class Solution
{
public static long[] productExceptSelf(int nums[], int n)
{
// code here
long ans[]=new long[n];
for(int i=0;i<n;i++){
long sum=1;
for(int j=0;j<n;j++){
if(i!=j){
sum*=nums[j];
}
}
ans[i]=sum;
}
return ans;
}
}

22>kth element in two arrays


input: arr1[]={2,3,6 7 9}
arr2[]={1,4,8,10};k=5
output=6
Explanation:
the final sorted array is 1,2,3,4,6,8,9,10
therefore the 5th element oth thir array is 6 ans
code:
class Solution {
public long kthElement( int arr1[], int arr2[], int n, int m, int k) {

int arr[] = new int[n+m];

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

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

Arrays.sort(arr);
return arr[k-1];
}
}

23>Allocate minimum number of pages


Input:
N = 4
A[] = {12,34,67,90}
M = 2
Output:113
Explanation:Allocation can be done in
following ways:
{12} and {34, 67, 90} Maximum Pages = 191
{12, 34} and {67, 90} Maximum Pages = 157
{12, 34, 67} and {90} Maximum Pages =113.
Therefore, the minimum of these cases is 113,
which is selected as the output.

code:
class Solution
{
public static int findPages(int[]A,int N,int M)
{

if(N<M){
return -1;
}
int low=0;
int high=0;

for(int i=0; i<A.length; i++){

if(A[i]>low){
low= A[i];
}

high+= A[i];
}

int res=-1;

while(low<=high){

int mid= (low+high)/2;

if(isAllocatable(A, mid, M)){


res=mid;
high= mid-1;
}else{
low= mid+1;
}

return res;
}

public static boolean isAllocatable(int[] A, int mid, int M){

int student=1;
int sum=0;

for(int i=0; i<A.length; i++){


if(sum+A[i]> mid){
student++;
sum=A[i];
}else{
sum+= A[i];
}

return student<=M;

}
};

24>Arithmetic Number
Input: A = 1, B = 3, C = 2
Output: 1
Explaination: 3 is the second term of the
sequence starting with 1 and having a common
difference 2.
code:
class Solution{
static int inSequence(int A, int B, int C){
// code here
if(C==0) return A==B ? 1 : 0;
else return (B-A)%C == 0 && (B-A)/C >= 0 ? 1 : 0;
}
}

***STRING/CHARACTER
1> Reverce a character?
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
code:
class Solution {
public void reverseString(char[] s) {
int start=0;
int end=s.length-1;
while(start<end)
{
char temp=s[start];
s[start]=s[end];
s[end]=temp;
start++;
end--;
}
}
}

2.Print all the duplicate characters in a string


Input: S = “geeksforgeeks”
output=g,e,k,s

code 1:without using char array


package ns;
import java.util.*;
class Ns
{
public static void main(String args[])
{
String s="geeksforgeeks";
int a=s.length();
char ch,ch1;
int i,j;
for(i=0;i<a;i++)
{
ch=s.charAt(i);
for(j=i+1;j<a;j++)
{
ch1=s.charAt(j);
if(ch==ch1)
{
System.out.println(ch1);
break;
}
}

}
}

with using char arrar[]


package ns;
import java.util.*;
class Ns
{
public static void main(String args[])
{
String s="geeksforgeeks";
int a=s.length();
char ch[]=s.toCharArray();
int i,j;
for(i=0;i<a;i++)
{
for(j=i+1;j<a;j++)
{
if(ch[i]==ch[j])
{
System.out.println(ch[j]);
break;
}
}

}
}

3.>Check if given strings are rotations of each other or not


Input: S1 = ABCD, S2 = CDAB
Output: Strings are rotations of each other

Input: S1 = ABCD, S2 = ACBD


Output: Strings are not rotations of each other
code:
package ns;
import java.util.*;
class Ns
{
public static void main(String args[])
{
String s1="ABCD";
String s2="CDAB";
if(s1.equalsIgnoreCase(s2))
{
System.out.println("Not rotated");
}
else
{
System.out.println("rotated");
}
}
}

4.>Print all subsequences of a string


nput : abc
Output : a, b, c, ab, bc, ac, abc

import java.util.*;
class Ns
{

static void printAllSubsequence(String input_str, String output_str){


if (input_str.length()==0) {
System.out.println( output_str );
return;
}
printAllSubsequence(input_str.substring(1), output_str +
input_str.charAt(0));
printAllSubsequence(input_str.substring(1), output_str);
}
public static void main(String args[]){
String output_str = "";
String input_str = "abcd";
printAllSubsequence(input_str, output_str);
}
}

5>Split the binary string into substrings with equal number of 0s and 1s
Input: str = “0100110101”
Output: 4
The required substrings are “01”, “0011”, “01” and “01”.
code:
class Solution {
public int countBinarySubstrings(String s) {
int count=0,count1=0;
int a=s.length();
int i,ans=0;
for(i=0;i<a;i++)
{
if(s.charAt(i)=='0')
{
count++;
}
else if(s.charAt(i)=='1')
{
count1++;
}
if(count==count1)
{
ans++;
}
}
return ans;
}
}

6>Isomorphic Strings:Ye basicalyy asa string hota h jisme ki hum ek string ke


element ko dusre string element se map kerte h ,aur dono string agar equal hota h
to return 1 .
class Solution
{
//Function to check if two strings are isomorphic.
public static boolean areIsomorphic(String str1,String str2)
{
// Your code here
HashMap<Character,Character> map=new HashMap<>();
int i;
if(str1.length()!=str2.length())return false;
for(i=0;i<str1.length();i++)
{
char ch=str1.charAt(i);
char ch2=str2.charAt(i);
if(map.containsKey(ch))
{
if(map.get(ch)!=ch2)return false;
}
else if(map.containsValue(ch2))

return false;
else
map.put(ch,ch2);
}
return true;

}
}

7.>string is a valid shuffle of two distinct strings?


ans :Shuffle string means Given two strings str1 and str2, and
a third-string shuffle, determine if shuffle is a valid shuffle of str1 and str2,
where a valid shuffle contains
all characters from str1 and str2 occurring the same number of times, regardless of
order. Print “YES” if valid, and “NO” otherwise.

code:
class Ns {
public static void main(String args[])
{

String str1="BA",str2="XY",shuffle="xyab";
String conc=str1.concat(str2);
if(conc.length()!=shuffle.length())
{
return;
}
char ch[]=conc.toCharArray();
Arrays.sort(ch);

char ch1[]=shuffle.toCharArray();
Arrays.sort(ch1);
String n=String.valueOf(ch);
String n1=String.valueOf(ch1);
System.out.println(n.equalsIgnoreCase(n1));
}
}

8.>Wildcard string matching


(wild card me 2 symbol ate h 1.* and 2nd ?,so * ka means ye hota h ki matching any
sequesnce of character and ? ka matlab ye h ki matching any matching character.
code:
class Solution{
static boolean match(String wild, String pattern)
{
String w = "";
for(int i =0 ; i< wild.length(); i++)
{
if(wild.charAt(i) == '?')//check if wild==? then just replace ? to all
the character form a-z
w+= "[a-z]";
else if(wild.charAt(i) == '*')check if wild==* then just replace * to
all the sequence of character form a-z
w+= "([a-z]*)*";
else
w+= wild.charAt(i);
}
return java.util.regex.Pattern.matches(w , pattern);//function used to
check the sequence?
}
}

9>Parenthesis Checker
input:({[]})
output true
package ns;
import java.util.*;
class Ns {
public static boolean helper(char a,char b)
{
return (
(a == '(' && b == ')') ||
(a == '{' && b == '}') ||
(a == '[' && b == ']')
);
}
static boolean ispar(String x)
{
int n=x.length();
Stack<Character>st=new Stack<>();
if(n==1)
return false;
for(int i=0;i<n;i++)
{
char k=x.charAt(i);
if(k=='('||k=='{'||k=='[')
{
st.push(k);
}
else {
if(st.isEmpty()==true)
{
return false;
}
else if(helper(st.peek(), k)==false)
{
return false;
}
else
{
st.pop();
}
}
}
return(st.isEmpty()==true);
}

public static void main(String args[])


{
String x="[([])}";
System.out.println(ispar(x));
}
}

10>String Pallendrom?
code:
class Solution {
int isPalindrome(String S) {
// code here
String rev="";
char ch;
int i;
for(i=S.length()-1;i>=0;i--)
{
rev=rev+S.charAt(i);
}
if(S.equalsIgnoreCase(rev))
{
return 1;
}
return 0;
}
};

after 1012 test case time complexity reached maximam


so ,
optimized code
class Solution {
int isPalindrome(String S) {

StringBuilder str = new StringBuilder(S);


String revStr = str.reverse().toString();

if(S.equals(revStr)){
return 1;
}
else{
return 0;
}

}
};

11.Count and say


isme basically asa hota h ki agar humare pas el string digit h "33221" to hume isme
ye count kerna h ki wo specific string kitne bar occour hua h.
eg 33221
33->count =2 3(the actual char)
232211(output);https://assets.leetcode.com/uploads/2020/10/23/countandsay.jpg

code:

class Solution {
public String countAndSay(int n) {
String s="1";
for(int i=2;i<n;i++)
{
s=CountAndAdd(s);
}
return s;
}
String CountAndAdd(String s)
{
StringBuilder curString=new StringBuilder();
char c=s.charAt(0);
int count=1;
for(int i=1;i<s.length();i++)
{
if(s.charAt(i)==c)
{
count++;
}
else
{
curString.append(count);
curString.append(c);
c=s.charAt(i);
count=1;
}
}
curString.append(count);
curString.append(c);
return curString.toString();
}
}

12>Longest Repeating Subsequence


Input:
str = "axxzxy"
Output: 2
Explanation:
The given array with indexes looks like
a x x z x y
0 1 2 3 4 5

The longest subsequence is "xx".


It appears twice as explained below.
Input:
str = "axxzxy"
Output: 2
Explanation:
The given array with indexes looks like
a x x z x y
0 1 2 3 4 5

The longest subsequence is "xx".


It appears twice as explained below.
code:
class Solution
{
public int LongestRepeatingSubsequence(String str)
{
// code here
char ch[]=str.toCharArray();
Arrays.sort(ch);
String s=String.valueOf(ch);
int count=0;
char ch1[]=s.toCharArray();
int i,j;
for(i=0;i<s.length();i++)
{
for(j=i+1;j<s.length();j++)
{
if(ch1[i]==ch1[j])
{
count++;
}
}
}
return count-1;
}
}

13.>Permutations of a given string


Input: ABC
Output:
ABC ACB BAC BCA CAB CBA

code:
package ns;
import java.util.*;
// A simple Java program for
// implementation of atoi
class Ns
{
public static void main(String args[])
{
String s="ABC";
permute(0,s);
}
public static String swap(String s,int a,int b)
{
char ch[]=s.toCharArray();
char p=ch[a];
ch[a]=ch[b];
ch[b]=p;
return String.valueOf(ch);
}
public static void permute(int index,String s)
{
//base case
if(index==s.length()-1)
{
System.out.println(s);
return;
}
for(int i=index;i<s.length();i++)
{
//swap
s=swap(s,i,index);
//recursion
permute(index+1,s);
//backtrack
s=swap(s,i,index);
}
}
}

14>Convert a sentence into its equivalent mobile numeric keypad sequence


Input: GEEKSFORGEEKS
Output: 4333355777733366677743333557777
code 1:
without using hashmap
package ns;
import java.util.*;
// A simple Java program for
// implementation of atoi
class Ns
{
public static void main(String args[])
{
String s="GEEKSFORGEEKS";
String temp="";
String
str[]={"2","22","222","3","33","333","4","44","444","5","55","555","6",
"66","666","7","77","777","7777","8","88","888","9","99","999","9999"};
for(int i=0;i<s.length();i++)
{
temp+=str[s.charAt(i)-'A'];
}
System.out.println(temp);
}
}

with using hash map

class Solution
{
String printSequence(String S)
{
Map<Character,Integer> map=new LinkedHashMap<>();
String str="";
map.put('A',2);
map.put('B',22);
map.put('C',222);
map.put('D',3);
map.put('E',33);
map.put('F',333);
map.put('G',4);
map.put('H',44);
map.put('I',444);
map.put('J',5);
map.put('K',55);
map.put('L',555);
map.put('M',6);
map.put('N',66);
map.put('O',666);
map.put('P',7);
map.put('Q',77);
map.put('R',777);
map.put('S',7777);
map.put('T',8);
map.put('U',88);
map.put('V',888);
map.put('W',9);
map.put('X',99);
map.put('Y',999);
map.put('Z',9999);
map.put(' ',0);

for(int i=0;i<S.length();i++)
{
str=str+map.get(S.charAt(i));
}
return str;
}
}

15.Count the Reversals


Input:
S = "}{{}}{{{"
Output: 3
Explanation: One way to balance is:
"{{{}}{}}". There is no balanced sequence
that can be formed in lesser reversals.

code:
class Sol
{
int countRev (String s)
{
// your code here
int open=0,close=0;
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
if(ch=='{')
{
open++;
}
else
{
if(open>0)
{
open--;
}
else
{
close++;
}
}
}
if((open+close)%2==1)return -1;
return(open/2)+(open%2)+(close/2)+(close%2);
}
}

16>Roman Number to Integer


I 1
V 5
X 10
L 50
C 100
D 500
M 1000

Example 1:

Input:
s = V
Output: 5
here if 1st char is smaller than its next char,then we just subtract it,otherwise
add
eg:a> we have to print IV in a int ,which is 4 but how ,so I->1 and V->5 so I-V
=5-1 :4 ans.
b>we have to print VI in a int,which is 6 but how ,so I->1 and V->5 so I-V
=5+1 :6 ans.
so for optimize code(O(1)),we used hash map.
code:
class Solution {
// Finds decimal value of a given roman numeral
public int romanToDecimal(String str) {
// code here
HashMap <Character,Integer> map=new HashMap<>();
map.put('I',1);
map.put('V',5);
map.put('X',10);
map.put('L',50);
map.put('C',100);
map.put('D',500);
map.put('M',1000);
int s=str.length();
int output=0;
for(int i=0;i<s;i++)
{
if(i<s-1 && map.get(str.charAt(i))<map.get(str.charAt(i+1)) )
{
output=output+map.get(str.charAt(i+1))-map.get(str.charAt(i));
i++;
}

else
{
output=output+map.get(str.charAt(i));
}
}
return output;
}
}

17>Longest Common Prefix


Input: strs = ["flower","flow","flight"]
Output: "fl"
code:
class Solution {
public String longestCommonPrefix(String[] strs) {
String prefix = strs[0];
for(int index=1;index<strs.length;index++){
while(strs[index].indexOf(prefix) != 0){
prefix=prefix.substring(0,prefix.length()-1);
}
}
return prefix;
}
}

18.Longest Common Subsequence


Input:
A = 6, B = 6
str1 = ABCDGH
str2 = AEDFHR
Output: 3
Explanation: LCS for input strings “ABCDGH” and “AEDFHR” is “ADH” of length 3.
isme basicalyy ye hota h ki dono string me jo common h aur jiska subsequence bhaout
bara h length me ,usee likhna h.
code:
class Ns
{
public static void main(String args[])
{
String s="ABCDGH";
String s1="AEDFHR";
System.out.println(longcommon(s, s1));

}
public static int longcommon(String s,String t)
{
if(s.length()==0||t.length()==0)
{
return 0;
}
if(s.charAt(0)==t.charAt(0))
{
return 1+longcommon(s.substring(1),t.substring(1));
}
else
{
int op=longcommon(s, t.substring(1));
int op1=longcommon(s.substring(1), t);
return Math.max(op,op1);
}
}
}

19.Find the disting element in an string?


code:
package ns;
import java.util.*;

class Ns{
public static void main(String args[])
{
String s="GEEKSGEEKSFOR";
HashSet<Character>hs=new HashSet<>();
int i;
for(i=0;i<s.length();i++)
{
hs.add(s.charAt(i));
}
int size=hs.size();
System.out.println(size);
}

20.Find the smallest window who contain all the string character itself.
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
code:
lass Solution {
public int findSubString( String str) {
// Your code goes here
HashSet<Character> hs=new HashSet<>();
for(int i=0;i<str.length();i++)
{
hs.add(str.charAt(i));
}
int distcount=hs.size();
int start=0,startIndex=0,min_len=Integer.MAX_VALUE;
int counter=0;
int visited[]=new int[256];
for(int i=0;i<str.length();i++)
{
visited[str.charAt(i)-65]++;//just map all the visited char directly
if(visited[str.charAt(i)-65]==1)counter++;//it char occour first time
then increased the counter
if(counter==distcount)//if out counter == distcount ,it means we got
our one window
{
while(visited[str.charAt(start)-65]>1)//we just srink our window
size
{
visited[str.charAt(start)-65]--;
start++;
}
int current=i-start+1;//our current window
if(current<min_len)
{
min_len=current;
startIndex=start;
}
}
}
return str.substring(startIndex,startIndex+min_len);
}
}

21.Remove Consecutive Characters


Input:
S = aabb
Output: ab
Explanation: 'a' at 2nd position is
appearing 2nd time consecutively.
Similiar explanation for b at
4th position.
Code:
class Solution{
public String removeConsecutiveCharacter(String S){
int a=S.length();
int i;
String ans="";
for(i=0;i<a;i++)
{
if(i<a-1 && S.charAt(i)==S.charAt(i+1))
{
continue;
}
else
{
ans=ans+S.charAt(i);
}
}
return ans;
}
}

22.>Edit Distance
Input:
s = "geek", t = "gesek"
Output: 1
Explanation: One operation is required
inserting 's' between two 'e's of s.

code:
class Solution {
public int editDistance(String s, String t) {

// Code here
int m=s.length();
int n=t.length();
int dp[][]=new int [m+1][n+1];
for(int i=0;i<=m;i++)dp[i][0]=i;
for(int j=0;j<=n;j++)dp[0][j]=j;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(s.charAt(i-1)==t.charAt(j-1))
{
dp[i][j]=dp[i-1][j-1];
}
else
{
dp[i][j]=1+Math.min(Math.min(dp[i][j-1], dp[i-1][j]),dp[i-1][j-
1]);
}
}
}
return dp[m][n];
}
}

LinkedList
Singly:
1>Insert a element in a first position in a linked list?
#include<iostream>
#include<stdlib.h>
using namespace std;
struct singly
{
int info;
struct singly*next;
};
typedef struct singly node;
node*create(node* start)
{
node*temp,*prev;
int v,d;
do
{
temp=(node*)malloc(sizeof(node));
if(temp==NULL)
{
exit(0);
}
else
{
cout<<"enter value for node\n";
cin>>v;
temp->info=v;
temp->next=NULL;
if(start==NULL)
{
start=temp;
}
else
{
prev->next=temp;
}
prev=temp;
}
cout<<"do you want to add more node,press 1 otherwise 0\n";
cin>>d;
}while(d==1);
return start;
}

node*insertFirst(node*start)
{
node*temp;
int v;
temp=(node*)malloc(sizeof(node));
if(temp==NULL)
{
exit(0);
}
else
{
cout<<"enter a value for node\n";
cin>>v;
temp->info=v;
temp->next=start;
start=temp;
}
return start;
}
node*display(node*start)
{
node*temp;
temp=start;
while(temp!=NULL)
{
cout<<"your data is"<<temp->info<<"\n";
temp=temp->next;
}
return start;
}
node*create(node*);
node*display(node*);
node*insertFirst(node*);
int main()
{
node* start=NULL;
int ch,d;
do
{
cout<<"1.Create/Add\n 2.Display\n 3.InsertFirst\n";
cout<<"Enter your choice\n";
cin>>ch;
switch(ch)
{

case 1:
start=create(start);
break;
case 2:
start=display(start);
break;
case 3:
start=insertFirst(start);
break;
default:
cout<<"invalid choice\n";
}
cout<<"do you want to access again press 1 other wise 0\n";
cin>>d;
}while(d==1);
return 0;
}

2>Delete from ll?


->>> Delete from first position
algo:-

node*delete first(node*start)
{
node*temp,*prev;
temp=start;
start=start->next;
temp->next=Null;
free(temp);
cout<<"data delete from first position
return start;
}

->>> Delete from last position


node*deleteLast(node*start)
{
node*temp,*prev;
temp=start;
prev=temp;
start=start->next;
while(temp->next!=Null)
{
prev->next=Null;
free(temp);
cout<<"data delete from last position\n";
}
return start;
}
3>Insert a data from last position?
code:
node*insertlast(node*start)
{
node*temp,*prev;
int v;
prev=start;
do
{
prev=prev->next;
}
while(prev->next!=NULL);
{
temp=(node*)malloc(sizeof(node));
if(temp==NULL)
{
exit(0);
}
else
{
cout<<"enter a value for node\n";
cin>>v;
temp->info=v;
temp->next=NULL;
prev->next=temp;
}
prev=temp;
}
return start;
}

4>Count a Length of Singly LinkedList?


Algo:
node*LengthCount(node*start)
{
node*temp=start;
int count=0;
while(temp!=NULL)
{
count++;
temp=temp->next;
}
cout<<"length will we "<<count<<"\n";
return start;
}

5>Search an element in an singly linked list?


code:
node*searchElement(node*start)
{
node*temp;
temp=start;
int target;cout<<"enter your target element"<<"\n";
cin>>target;
while(temp!=NULL)
{
if(temp->info==target)
{
cout<<"1"<<"\n";
break;
}
temp=temp->next;
if(temp->info!=target)
{
cout<<"0"<<"\n";
break;
}
}
return start;
}
6>Reverse a singly linkedList?
algo:
node*rev(node*start)
{
node*temp,*prev,*nxt;
temp=start;
prev=NULL;
while(temp!=NULL)
{
nxt=temp->next;
temp->next=prev;
prev=temp;
temp=nxt;
}
start=prev;
return start;
}
7>Middle Element in an Singly LinkedList?
algo:
node*Middle(node*start)
{
node*prev,*temp;
prev=temp=start;
if(start==NULL)
{
cout<<"Empty List\n";
exit(0);
}
else
{
while(temp!=NULL && temp->next!=NULL)
{
prev=prev->next;
temp=temp->next->next;
}
cout<<prev->info<<"\n";
}
return start;
}

8>Check Cycle in a singly LinkedList?


algo:
node*Cycle(node*start)
{
node*prev,*temp;
prev=start;
temp=start->next;
if(start==NULL||start->next==NULL)
{
return false;
}
while(prev!=temp)
{
if(temp==NULL && temp->next==NULL)
{
return false;
}
prev=prev->next;
temp=temp->next->next;
}
return true;
return start;
}

9>Check a Singly LinkedList is pallendrom or not?


algo:
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode*slow,*fast;
//find a middle element
slow=fast=head;
while(fast!=NULL && fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}//here we got our middle element as slow
if(fast!=NULL && fast->next==NULL)
{
slow=slow->next;//for odd case
}
//reverce a ll
ListNode *prev,*nxt;
prev=NULL;
while(slow!=NULL && slow->next!=NULL)
{
nxt=slow->next;
slow->next=prev;
prev=slow;
slow=nxt;
}
if(slow!=NULL)
{
slow->next=prev;
}
fast=head;
//compare and display a result
while(slow!=NULL && fast!=NULL)
{
if(slow->val!=fast->val)
{
return false;
}
slow=slow->next;
fast=fast->next;
}
return true;
}
};

10>Segregate Even And Odd Nodes In a Linked List?


Sample Input 1
2 1 3 5 6 4 7

Sample Output 1
2 6 4 1 3 5 7

algo:
Node* segregateEvenOdd(Node* head)
{
Node*even=NULL;
Node*odd=NULL;
Node*e=NULL;
Node*o=NULL;
while(head)
{
if(head->data%2==0)
{
if(even==NULL)
{
even=head;
e=head;
}
else
{
e->next=head;
e=e->next;
}
}
else
{
if(odd==NULL)
{
odd=head;
o=head;
}
else
{
o->next=head;
o=o->next;
}
}
head=head->next;
}
if(e) e->next=odd;
if(o) o->next=NULL;
if(even) return even;
return odd;
}

11.>Delete a middle element from linked list ?


code:
node*deleteMiddle(node*start)
{
node*slow,*fast,*prev;
slow=fast=start;
prev=NULL;
if(start==NULL ||start->next==NULL)return NULL;
while(fast!=NULL && fast->next!=NULL)
{
prev=slow;
slow=slow->next;
fast=fast->next->next;
}
prev->next=prev->next->next;
cout<<"data delete from middle position\n";
return start;
}
12.Remove N-th node from the end of a Linked List?
algo:
Node* removeKthNode(Node* head, int K)
{
// Write your code here.
Node*slow=head,*fast=head;
while(K--)
{
fast=fast->next;//it represent a gap in how much we want to delete
}
if(fast==NULL)
{
return slow->next;
}
while(fast->next!=NULL)
{
slow=slow->next;
fast=fast->next;
}
slow->next=slow->next->next;
return head;
}

13.Sum at last 1 if only last digit/vlaue is one?


eg:152 <------ after add one ----->> 153
algo:
node*addOne(node*start)
{
node*temp;
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
if(temp->info<9)
{
temp->info=temp->info+1;
}
cout<<"Sum Succesfully....\n";
return start;
}

14>Add one to a number represented as Linked List?


Sample Input 1:
1 5 2
Sample Output 1:
1 5 3

algo:
class Solution
{
public:
Node*revese(Node*head)
{
Node*prev,*curr,*nxt;
prev=NULL;
curr=head;
nxt=NULL;
while(curr!=NULL)
{
nxt=curr->next;
curr->next=prev;
prev=curr;
curr=nxt;
}
return prev;
}

Node* addOne(Node *head)


{
head=Node*reverse(head);

Node*curr,*prev;
curr=prev=head;
int sum=curr->data+1;
curr->data=sum%10;
int carry=sum/10;

curr=curr->next;

while(curr!=NULL)
{
sum=curr->data+carry;
curr->data=sum%10;
carry=sum/10;
prev=curr;
curr=curr->next;
}
if(carry!=0)
{
prev->next=(Node*)malloc(sizeof(carry));
}
head=Node*reverse(head);
return head;
}
};

15.Add Two LinkedList?


Input:
nums1:1->2->3->NULL
nums2:4->5->6->NULL
output:5->7->9->NULL
algo:
Node *addTwoNumbers(Node *num1, Node *num2)
{
Node*ans=new Node(0);
Node*p=num1,*q=num2,*current=ans;
int carry=0;
while(p!=NULL || q!=NULL)
{
int x=(p!=NULL)?p->data:0;
int y=(q!=NULL)?q->data:0;
int sum=carry+x+y;
carry=sum/10;
current->next=new Node(sum%10);
current=current->next;
if(p!=NULL)p=p->next;
if(q!=NULL)q=q->next;
}
if(carry>0)
{
current->next=new Node(carry);
}
return ans->next;
}

16.Remove Duplicates from Sorted List?


algo:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode*current=head;
if(current==NULL)
{
return head;
}
else
{
while(current!=NULL &&current->next!=NULL)
{
if(current->val==current->next->val)
{
ListNode*temp=current->next;
current->next=current->next->next;
delete(temp);//jo duplicate h wo extra space lee reha h to hum
usko remove ker rehe h.
}
else
{
current=current->next;
}
}
}
return head;

}
};

17.>Intersection of Two Linked Lists?


sol:-Iss question me hume 2 ll given h,hume ye batana h ki intersecting point kon
sa h.
approach:hum jante h ki intersecting point asa point h jis point pe dono ll aye ga
to hum agar conpare kerte h ki agar LL1 ka address agar
LL2 se match ker gaya to wahi mera intersecting point h.
algo:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int a=0,b=0;
ListNode*current=headA; /*
while(current)
{
a++;
current=current->next;
}
current=headB;
while(current)
{
b++;
current=current->next;
} Yaha pe hum ye check ker rehe h ki dono
ll ka length kitna h ,kyu ki agar compare kerna h to same length
hona chahiye ,to length find kerke
usko barabar ker ker rehe h .
int diff=abs(a-b);
if(a<b)
{
while(diff--)
{
headB=headB->next;
}
}
else
{
while(diff--)
{
headA=headA->next;
} */
}
while(headA and headB)
{
if(headA==headB)
{
return headA;
}
else
{
headA=headA->next;
headB=headB->next;
}
}
return NULL;
}
};

18>Reverse List In K Groups?


Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
algo:
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* prev=NULL;
ListNode* current=head;
ListNode* nxt;
int count=0;
while(current!=NULL and count<k)
{
nxt=current->next;
current->next=prev;
prev=current;
current=nxt;
count++;
}
if(nxt!=NULL)
head->next=reverseKGroup(nxt,k);
return prev;

}
};
19>Rotate List?
Input: head = [0,1,2], k = 4
Output: [2,0,1]
basically iska appoach ye h ki hum ek formula ka used kerke [loop=k%n ,where n is
the size of ll and k is the give no]
ye pata kerlenge ki actual kitna bar move kerna h the loop=n-loop used kerke
starting data find kerlenge ki rest starting
kitna data bacha h ,then waha tk loop chala ke uske bd wale ko fist position pe dal
denge.
1->2->3->4->5
k=2
n=5
loop:k%n=2%5=>2;//hume last 2 element ko phele lana h
loop=n-loop ->5-2=3//hum starting ke three element ke bd ka element ko aage le
ayange.
:- 4->5->1->2->3.

algo:
class Solution {
public:
int size(ListNode*head)
{
int n=0;
while(head!=NULL)
{
n++;
head=head->next;
}
return n;
}
ListNode* rotateRight(ListNode* head, int k) {
if(head==NULL)return head;
int n=size(head);

int loop=k%n;
loop=n-loop;

if(n==1 ||loop==n)
return head;

int j=0;
ListNode*temp=head;
ListNode*firstaddress=head;

while(temp!=NULL)
{
j++;
if(j==loop)
{
firstaddress=temp->next;
temp->next=NULL;
break;
}
temp=temp->next;
}

temp=firstaddress;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=head;
return firstaddress;
}
};

**Doubly**
1.>Create a Doubly LL?
algo:
node*create(node*start)
{
node*temp,*prev;
int v,d;
do
{
temp=(node*)malloc(sizeof(node));
if(temp==NULL)
{
cout<<"unable to create a node\n";
exit(0);
}
else
{
cout<<"enter a value for node\n";
cin>>v;
temp->info=v;
temp->left=NULL;
temp->right=NULL;
if(start==NULL)
{
start=temp;
}
else
{
prev->right=temp;
temp->left=prev;
}
prev=temp;
}
cout<<"do you want to add again press 1 otherwise 0\n";
cin>>d;
}while(d==1);
return start;
}

2>Insert An Element?
->>>Insert First
algo:
node*insertFirst(node*start)
{
node*temp;
int v;
temp=(node*)malloc(sizeof(node));
if(temp==NULL)
{
cout<<"unable to create a node\n";
exit(0);
}
else
{
cout<<"enter a value for node\n";
cin>>v;
temp->info=v;
temp->left=NULL;
temp->right=start;
temp->right->left=temp;
start=temp;
cout<<"data inserted at first position\n";
}
return start;
}
->>>InsertLast
algo:
node*insertLast(node*start)
{
node*temp,*prev;
int v,d;
prev=start;
do
{
prev=prev->right;
}
while(prev->right!=NULL);
{
temp=(node*)malloc(sizeof(node));
if(temp==NULL)
{
cout<<"unable to create a node\n";
}
else
{
cout<<"enter a value for node\n";
cin>>v;
temp->info=v;
temp->right=NULL;
temp->left=prev;
prev->right=temp;
cout<<"data inserted at last position\n";
}
prev=temp;
}
return start;
}

3>Delete a node from Doubly ll


algo:
->>>Delete First
node*deleteFirst(node*start)
{
node*temp;
temp=start;
start=start->right;
temp->right->left=NULL;
temp->right=NULL;
free(temp);
cout<<"data delete from first position\n";
return start;
}

->>>Delete Last
node*deleteLast(node*start)
{
node*temp;
temp=start;
do
{
temp=temp->right;
}
while(temp->right!=NULL);
{
temp->left->right=NULL;
temp->left=NULL;
free(temp);
cout<<"data deleted from last position\n";
}
return start;
}

4>Display a element?
algo:
node*display(node*start)
{
node*temp;
temp=start;
while(temp!=NULL)
{
cout<<temp->info<<"\n";
temp=temp->right;
}
return start;
}

5>Reverce a double ll?


algo:
node*rev(node*start)
{
node*temp,*prev,*next;
prev=NULL;
temp=start;
while(temp!=NULL)
{
next=temp->right;
temp->right=prev;
prev=temp;
temp=next;
}
start=prev;
return start;
}

6>Middle Element in an Doubly LinkedList?


algo:
node*Middle(node*start)
{
node*prev,*temp;
prev=temp=start;
if(start==NULL)
{
cout<<"Empty List\n";
exit(0);
}
else
{
while(temp!=NULL && temp->right!=NULL)
{
prev=prev->right;
temp=temp->right->right;
}
cout<<prev->info<<"\n";
}
return start;
}
7>Find pairs with given sum in doubly linked list?
algo:
//here we used two pointer approach just like in a array
// 1<->2<->3<->4<-><->5
// first last
node*FindPair(node*start)
{
node*first=head;
node*second=head;
int x=7;
while(second->right!=NULL)
second=second->right;

bool found=false;

while(first!=second && second->right!=first)


{
if((first->info+second->info)==x)
{
found=true;
cout<<first->info+"\t"<<second->info;
first=first->right;
second=second->prev;
}
else if((first->info+second->info)<x)
{
first=first->right;
}
else
{
second=second->prev;
}
}
if(found==false)
{
cout<<"no pair found\n";
}
return start;
}
FULL code:
//doubly ll
#include<iostream>
#include<stdlib.h>
using namespace std;

struct doubly
{
int info;
struct doubly*left;
struct doubly*right;
};
typedef struct doubly node;

node*create(node*start)
{
node*temp,*prev;
int v,d;
do
{
temp=(node*)malloc(sizeof(node));
if(temp==NULL)
{
cout<<"unable to create a node\n";
exit(0);
}
else
{
cout<<"enter a value for node\n";
cin>>v;
temp->info=v;
temp->left=NULL;
temp->right=NULL;
if(start==NULL)
{
start=temp;
}
else
{
prev->right=temp;
temp->left=prev;
}
prev=temp;
}
cout<<"do you want to add again press 1 otherwise 0\n";
cin>>d;
}while(d==1);
return start;
}

node*insertFirst(node*start)
{
node*temp;
int v;
temp=(node*)malloc(sizeof(node));
if(temp==NULL)
{
cout<<"unable to create a node\n";
exit(0);
}
else
{
cout<<"enter a value for node\n";
cin>>v;
temp->info=v;
temp->left=NULL;
temp->right=start;
temp->right->left=temp;
start=temp;
cout<<"data inserted at first position\n";
}
return start;
}
node*insertLast(node*start)
{
node*temp,*prev;
int v,d;
prev=start;
do
{
prev=prev->right;
}
while(prev->right!=NULL);
{
temp=(node*)malloc(sizeof(node));
if(temp==NULL)
{
cout<<"unable to create a node\n";
}
else
{
cout<<"enter a value for node\n";
cin>>v;
temp->info=v;
temp->right=NULL;
temp->left=prev;
prev->right=temp;
cout<<"data inserted at last position\n";
}
prev=temp;
}
return start;
}
node*deleteFirst(node*start)
{
node*temp;
temp=start;
start=start->right;
temp->right->left=NULL;
temp->right=NULL;
free(temp);
cout<<"data delete from first position\n";
return start;
}
node*deleteLast(node*start)
{
node*temp;
temp=start;
do
{
temp=temp->right;
}
while(temp->right!=NULL);
{
temp->left->right=NULL;
temp->left=NULL;
free(temp);
cout<<"data deleted from last position\n";
}
return start;
}
node*display(node*start)
{
node*temp;
temp=start;
while(temp!=NULL)
{
cout<<temp->info<<"\n";
temp=temp->right;
}
return start;
}
node*create(node*);
node*display(node*);
node*insertFirst(node*);
node*insertLast(node*);
node*deleteFirst(node*);
node*deleteLast(node*);
int main()
{
node*start=NULL;
int ch,d;
do
{
cout<<"1.create\n 2.display\n 3.insertFirst\n 4.insertLast\n 5.DeleteFirst\
n 6.DeleteLast\n";
cout<<"enter your choice\n";
cin>>ch;
switch(ch)
{
case 1:
start=create(start);
break;
case 2:
start=display(start);
break;
case 3:
start=insertFirst(start);
break;
case 4:
start=insertLast(start);
case 5:
start=deleteFirst(start);
break;
case 6:
start=deleteLast(start);
break;
default:
cout<<"invalid choice\n";
}
cout<<"do you wan to access again press 1 otherwise 0\n";
cin>>d;
}while(d==1);
return 0;
}

**Bit Manipulation
Binary Representation.
1> 23=(10111)2
Now we have to convert it into decimal
=1*2^4+0*2^3+1*2^2+1*2^1+1*2^0
=16+0+4+2+1
=23
so this is how we convert binary into decimal.

ans if we want to convert decimal to binary then we have to just divide that
sepecific decimal no from binary no and the remainder is says as binary no.
BitWise Operator
There are basically 6 type of operator
1>Not(~):It is an unary operator.
unary operator asa operator hota h jo sirf one operand me used hota h.
eg:
6=(110)2
~6=~(110)2=(001)2=1

so basically ye kerta ye h ki 1 ko 0 ns 0 ko 1 ker dete h.

2>And(&):It is an binary operetor.(Asa operator jo 2 operand ke sath km kere.


1 & 1=1
1 & 0=0
0 & 1=0
0 & 0=0

3>OR(|):It is an binary operetor.(Asa operator jo 2 operand ke sath km kere.


1 | 1=1
1 | 0=1
0 | 1=1
0 | 0=0

4>XOR(^)=It is an binaru operator.


1 ^ 1=0
1 ^ 0=1
0 ^ 1=1
0 ^ 0=0

5>Left Shift(<<):element to left shift kerna 0<-0<-0<-1<-1<-1<-1<-1<-1<-0<-0 new


value

6>5>Right Shift(>>):element to right shift kerna new value 0->0->0->1->1->1->1-


>1->1->0->0

Questions.
1>Even or odd no using bitwise operator
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int ans=(n&1);
if(ans==1)
{
System.out.println("odd no");
}
else
{
System.out.println("even no");
}

so basically ye ase work: ki and operator kb hi one deta h jb both 1 ho


01101
& 1
-----
00001//so yaha pe upper me 1 and lower me 1 match ker gaya h.

10100
1
-----
00000
To is question me hum hum bs ans me simply check ker liye ki agar n & 1==1 hota h
to wo odd h ni to even.

**STACK
1.Implement a stack using array
code no1:
#include <stack>
class Stack {

public:
int size;
stack<int>st;
Stack(int capacity) {
// Write your code here.
size=capacity;
}

void push(int num) {


// Write your code here.
if(st.size()!=size)
{
st.push(num);
}
}

int pop() {
// Write your code here.
if(st.size()>0)
{
int ans=st.top();
st.pop();
return ans;
}
return -1;
}

int top() {
// Write your code here.
if(st.size()>0)
{
return st.top();
}
return -1;
}

int isEmpty() {
// Write your code here.
return st.empty();
}

int isFull() {
// Write your code here.
return (st.size()==size);
}

};

code no2:
1>stack using array
#include<iostream>
using namespace std;
struct stack
{
int size;
int top;
int *S;
};

void create(struct stack *st)


{
cout<<"enter size of stack\n";
cin>>st->size;
st->top=-1;
st->S=(int *)malloc(st->size*sizeof(int));
cout<<"stack is created\n";
}

void pushh(struct stack *st)


{
int n;
if(st->top==st->size-1)
{
cout<<"stack is empty\n";
}
else
{
cout<<"enter value for stack\n";
cin>>n;
st->top++;
st->S[st->top]=n;
}
cout<<"data stored\n";
}
void popp(struct stack *st)
{
int a=-1;
if(st->top==-1)
{
cout<<"stack is empty\n";
}
else
{
a=st->S[st->top];
st->top--;
}
cout<<"element is deleted\n";
}
void peek(struct stack *st)
{
int a=-1;
if(st->top==-1)
{
cout<<"stack is empty\n";
}
else
{
a=st->S[st->top];
cout<<"peek element is"<<a<<"\n";
}
}
void display(struct stack st)
{
for(int i=st.top;i>=0;i--)
{
cout<<st.S[i]<<"\n";
}
}

int main()
{
struct stack st;
int ch,d;
do
{
cout<<"1.create\n 2.push\n 3.display\n 4.delete\n 5.peek element\n";
cout<<"enter your choice\n";
cin>>ch;
switch(ch)
{
case 1:
create(&st);
break;
case 2:
pushh(&st);
break;
case 3:
display(st);
break;
case 4:
popp(&st);
break;
case 5:
peek(&st);
break;
default:
cout<<"invalid choice\n";
}
cout<<"do you want to used again press 1 otherwise 0\n";
cin>>d;
}
while(d==1);
return 0;
}

2>Stack using linked list


code:
#include<bits/stdc++.h>
using namespace std;

struct Node
{
int info;
Node* next;
};

class mystack
{
Node* head;
int stacksize;
public:

mystack()
{
head=NULL;
stacksize=0;
}

void push(int g)
{
Node* temp=new Node();
temp->info=g;
temp->next=head;
head=temp;

cout<<"Element "<<g<<" pushed into the stack!"<<endl;


stacksize++;
}

void pop()
{
if(head==NULL)
{
cout<<"Stack is Empty! Cannot POP an Element!"<<endl;
return;
}

Node* temp=head;
head=temp->next;
temp->next=NULL;
delete temp;
cout<<"Element Popped!"<<endl;
stacksize--;
}

int top()
{
if(head==NULL)
{
cout<<"NO TOP ELEMENT! Stack is empty!"<<endl;
return -1;
}

cout<<"Top Element is: "<<head->val<<endl;


return head->val;
}

int size()
{
cout<<"Size of Stack is: "<<stacksize<<endl;
return stacksize;
}

int empty()
{
if(head==NULL)
{
cout<<"Stack is Empty!"<<endl;
return 1;

cout<<"Stack is NOT EMPTY!"<<endl;


return 0;
}
};

int main()
{

mystack s1;

s1.empty();

s1.push(7);

s1.push(9);

s1.pop();

s1.push(10);

s1.top();

s1.size();

s1.empty();

return 0;
}

3.Parenthesis matchng
#include<bits/stdc++.h>
using namespace std;
bool isValid(string s)
{
int n=s.size();
stack<char>st;
bool ans=true;
for(int i=0;i<n;i++)
{
if(s[i]=='('||s[i]=='{'||s[i]=='[')
{
st.push(s[i]);
}
else if(s[i]==')')
{
if(!st.empty() and st.top()=='(')
{
st.pop();
}
else
{
ans=false;
break;
}
}

else if(s[i]=='}')
{
if(!st.empty() &&st.top()=='{')
{
st.pop();
}
else
{
ans=false;
break;
}
}

else if(s[i]==']')
{
if(!st.empty() &&st.top()=='[')
{
st.pop();
}
else
{
ans=false;
break;
}
}
}
if(!st.empty())
{
return false;
}
else
{

return ans;
}
}
int main()
{
string s="{([])}";
if(isValid(s))
{
cout<<"valid string\n";
}
else
{
cout<<"invalid string\n";
}
return 0;
}

3>Min Stack
basically min stack ka matlab ye hota h ki hume stack me min nikalna h in o(1)
code:
class MinStack {
public:

stack<int>st, s2;
MinStack() {

void push(int val) {


if( s2.empty() || val <= s2.top() ){
s2.push(val);
}

st.push(val);
}

void pop() {

if(st.top() == s2.top()){
s2.pop();
}
st.pop();

int top() {
return st.top();
}

int getMin() {
return s2.top();
}
};
4>Infix prefix and postfix conversion ?
before knowing it we have to know about its priority
therefore:-
I-->()
II->*
III->\
IV-->+
V-->-
**>infix to postfix conversion
((a+b)+(c*d))
->((a+b)+(cd*))
->((ab+))+(cd*))
->ab+cd*+ ans

in prefix
->((a+b)+(*cd))
->((+ab))+(*cd))
->++ab*cd ans

**code:
//infix to postfix
#include<iostream>
#include<stack>
using namespace std;

int pre(char c)
{
if(c=='^')
{
return 3;
}
else if(c=='/'||c=='*')
{
return 2;
}
else if(c=='+'||c=='-')
{
return 1;
}
else
{
return 0;
}
}
string infixtopostfix(string s)
{
stack<char>st;
string ans;
for(int i=0;i<s.length();i++)
{
if ((s[i] >= 'a' && s[i] <= 'z' || s[i] >= 'A' && s[i] <= 'Z'))
{
ans+=s[i];
}
else if(s[i]=='(')
{
st.push(s[i]);
}
else if(s[i]==')')
{
while(st.top()!='(')
{
ans+=st.top();
st.pop();
}
st.pop();
}
else
{
while(!st.empty() && pre(s[i])<=pre(st.top()))
{
ans+=st.top();
st.pop();
}
st.push(s[i]);
}
}
while(!st.empty())
{
ans+=st.top();
st.pop();
}
return ans;
}
int main()
{
string exp = "(a-b/c)*(a/k-l)";
cout<<infixtopostfix(exp);
return 0;
}

code:**infix to prefix (there is only one change ans hume starting and ending me
stack element ko reverse kerna h
and ( ka position change kerna h means agar closing h to opning and opning h to
closing

//infix to prefix
#include<iostream>
#include<stack>
#include<algorithm>
using namespace std;

int pre(char c)
{
if(c=='^')
{
return 3;
}
else if(c=='/'||c=='*')
{
return 2;
}
else if(c=='+'||c=='-')
{
return 1;
}
else
{
return 0;
}
}
string infixtoprefix(string s)
{
reverse(s.begin(),s.end());
stack<char>st;
string ans;
for(int i=0;i<s.length();i++)
{
if ((s[i] >= 'a' && s[i] <= 'z' || s[i] >= 'A' && s[i] <= 'Z'))
{
ans+=s[i];
}
else if(s[i]==')')
{
st.push(s[i]);
}
else if(s[i]=='(')
{
while(st.top()!=')')
{
ans+=st.top();
st.pop();
}
st.pop();
}
else
{
while(!st.empty() && pre(s[i])<=pre(st.top()))
{
ans+=st.top();
st.pop();
}
st.push(s[i]);
}
}
while(!st.empty())
{
ans+=st.top();
st.pop();
}
reverse(ans.begin(),ans.end());
return ans;
}
int main()
{
string exp = "(a-b/c)*(a/k-l)";
cout<<infixtoprefix(exp);
return 0;
}

**postfix to infix:- insme bascally ye kerna h ki operand ko push kerna h stack me


then agar operator ata h to 2 operand ko pop kerna h stack se
then us dono ke bich me wo operand ko laga dena h then bracketr ko assign kerke
phir se push kerna h stack me.
code:
#include <iostream>
#include <stack>
using namespace std;
bool isOperand(char c)
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
return true;
}
else {
return false;
}
}
string PostfixToInfix(string postfix)
{
stack<string> s;
for (int i = 0; i < postfix.length(); i++) {
if (isOperand(postfix[i])) {
string op(1, postfix[i]);
//string op=postfix[i];
s.push(op);
}
else {
string op1 = s.top();
s.pop();
string op2 = s.top();
s.pop();
s.push("(" + op2 + postfix[i] + op1 + ")");
}
}

return s.top();
}
int main()
{

string infix, postfix;


cout << "Enter a POSTFIX Expression :" << endl;
cin >> postfix;
cout << "POSTFIX EXPRESSION: " << postfix << endl;
infix = PostfixToInfix(postfix);
cout << endl
<< "INFIX EXPRESSION: " << infix;

return 0;
}

**prefix to infix:-basically ye same as a postfix to prefix ka bs ye difference h


ki hume apna itiration ending se 1st tk leke jana h
then op1 + operator + op2
code:
#include <iostream>
#include <stack>

using namespace std;


bool isOperand(char c)
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
return true;
}
else {
return false;
}
}
string PrefixToInfix(string prefix)
{
stack<string> s;
for (int i = prefix.length()-1; i>=0; i--) {
if (isOperand(prefix[i])) {
string op(1, prefix[i]);
//string op=postfix[i];
s.push(op);
}
else {
string op1 = s.top();
s.pop();
string op2 = s.top();
s.pop();
s.push("(" + op1 + prefix[i] + op2 + ")");
}
}

return s.top();
}
int main()
{
string infix, prefix;
cout << "Enter a PREFIX Expression :" << endl;
cin >> prefix;
cout << "PREFIX EXPRESSION: " << prefix << endl;
infix = PrefixToInfix(prefix);
cout << endl
<< "INFIX EXPRESSION: " << infix;
return 0;
}

**>Implelemt a stack using queue?

code:
class MyStack {
public:
queue<int>q1,q2;

MyStack() {

void push(int x) {
while(!q1.empty()){
q2.push(q1.front());
q1.pop();
}
q1.push(x);
while(!q2.empty()){
q1.push(q2.front());
q2.pop();
}

int pop() {
int val = q1.front();
q1.pop();
return val;

int top() {
return q1.front();
}

bool empty() {
return q1.empty();
}
};

**>Next Greater Element:


Example 1:

Input: N = 11, A[] = {3,10,4,2,1,2,6,1,7,2,9}

Output: 10,-1,6,6,2,6,7,7,9,9,10

Explanation: For the first element in A ,i.e, 3, the greater element which comes
next to it while traversing and is closest to it is 10.
Hence,10 is present on index 0 in the resultant array.Now for the second
element,i.e, 10, there is no greater number and hence -1 is it’s
next greater element (NGE). Similarly, we got the NGEs for all other elements
present in A.

logic:-*traverse a array from last to 1st


*take a array variable who store ans
*create a stack
*check if stack is empty initially then assign ans=-1 and push the
upcomming array element into stack.
*if(n[i]<st.top()),here we get our greater no ,just add it into ans and
push n[i] into stack
*if(n[i]>st.top()), pop the element until there is no greater element
present under stack if greter element found then add it into ans ans push n[i]
code:
class Solution
{
public:
//Function to find the next greater element for each element of the array.
vector<long long> nextLargerElement(vector<long long> arr, int n){
// Your code here
vector<long long> ans(n,-1);// n ko -1 se initialize ker diye
stack<long long>st;
for(int i=n-1;i>=0;i--)
{
while(!st.empty() && st.top()<=arr[i])
{
st.pop();
}
if(st.empty()==false )ans[i]=st.top();
st.push(arr[i]);
}
return ans;

};

**Asteroid Collision:
For each asteroid, the absolute value represents its size, and the sign represents
its direction
(positive meaning right, negative meaning left). Each asteroid moves at the same
speed.
Find out the state of the asteroids after all collisions. If two asteroids meet,
the smaller one
will explode. If both are of same size, both will explode. Two asteroids moving in
the same direction will never meet.

logic :-if(n[i]>0 && st.top>0) just push n[i] into stack


if(n[i]<0 && st.top<0) just push n[i] into stack
if(n[i]<0 && st.top()>0), so here collisions occour
so just check who is greater after submission, if st.top is
small just pop it, if n[i]<st.top, so no need to pop just break;
if both are same just pop st.top and assign break.

code:
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
stack<int> st;

for(int &a : asteroids) {

while(!st.empty() && a < 0 && st.top() > 0) {


int sum = a + st.top();
if(sum < 0) {
st.pop();
} else if(sum > 0) {
a = 0;
break;
} else {
st.pop();
a = 0;
}
}
if(a != 0)
st.push(a);

}
int s = st.size();
vector<int> result(s);
int i = s-1;
while(!st.empty()) {
result[i] = st.top();
st.pop();
i--;
}

return result;
}
};
or

class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
stack<int> st;
for (int i=0;i<asteroids ;i++)
{
if(st.empty()==true)
{
st.push(asteroids[i]);
}
else if(asteroids[i]>0 &&st.top()>0 || asteroids[i]<0 &&st.top()<0)
{
st.push(asteroids[i]);
}
else if(st.top()>0 && asteroids[i]<0)
{
while(!st.empty())
{
int sum=asteroids[i]+st.top();
if(sum<0)
{
st.pop();
}
else if(sum>0)
{
break;
}
else
{
st.pop();
break;
}
}
}
}
int s=st.size();
vector<int> result(s);
int i = s-1;
while(!st.empty()) {
result[i] = st.top();
st.pop();
i--;
}

return result;
}
};

**>Remove K Digits
logic:
->if stack ka top>n[i], so pop st.top until st in not empty and k is not = 0
and decreased k by 1
else
push n[i] in to stack
->after that one more time check is while(k>0), pop element from stack and
decreased k by 1.
->take a stirng ans and insert all element of stack and just reverse the ans
and display ans.
code:
class Solution {
public:
string removeKdigits(string S, int K) {
int n = S.length();
if(K==n) {
return "0";
}
stack<char>st;
for(int i=0;i<n;i++) {
while(!st.empty() && K>0 && st.top()>S[i]) {
st.pop();
K--;
}
st.push(S[i]);
}
while(K>0) {
st.pop();
K--;
}
string ans = "";
while(!st.empty()) {
ans += st.top();
st.pop();
}
reverse(ans.begin(),ans.end());
int i;
for(i=0;i<ans.size();i++) {
if(ans[i]!='0') {
break;
}
}
if(i==ans.size()) {
return "0";
}
return ans.substr(i);
}
};

**>Sliding Window Maximum?


Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
by using stack:
code:
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
stack<int>st;
int max=0;
int a=nums.size()-k;
for(int i=0;i<=a;i++)
{
max=nums[i];
for(int j=1;j<k;j++)
{
if(nums[i+j]>max)
{
max=nums[i+j];
}
}
st.push(max);
}
//for reversr a stack value
int s=st.size();
vector<int>result(s);
int i=s-1;
while(!st.empty())
{
result[i]=st.top();
st.pop();
i--;
}
return result;
}
};
but only problem with stack in this code is that it take very time to execute.So
for solving this we used monotonic dequeue.
therefore:
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int n = nums.size();

deque<int> dq;
vector<int> ans;
for(int i = 0; i < n; i++) {
//remove all elements from queue which is smaller than nums[i]
while(!dq.empty() && nums[dq.back()] <= nums[i]) {
dq.pop_back();
}

// push cur element


dq.push_back(i);

// check if there is out of window element at front


if(dq.front() == i - k) {
dq.pop_front();
}

// Get max element for cur window


if(i >= k - 1) {
ans.push_back(nums[dq.front()]);
}
}
return ans;
}
};
**remove the balls
Input:
N = 3
color[] = {2, 2, 5}
radius[] = {3, 3, 4}
Output:
1
Explanation:
First ball and second ball have same color 2 and
same radius 3.So,after removing only one ball
is left.It could not be removed from the array.
Hence, the final array has length 1.
code:
class Solution {
public:
int finLength(int N, vector<int> color, vector<int> radius) {
stack<int> c,r ;
c.push(color[0]);
r.push(radius[0]);
for(int i=1;i<N;i++){
if(c.empty() || c.top() != color[i] || r.top() != radius[i]){
c.push(color[i]);
r.push(radius[i]);
}

else { c.pop();r.pop();}

}
return c.size();
}
};

--->QUEUE
**>Queue using array
code:
//queue using array
#include<iostream>
using namespace std;
struct que
{
int size;
int front;
int rear;
int *Q;

};

void create(struct que *q)


{
cout<<"enter your size\n";
cin>>q->size;
q->front=-1;
q->rear=-1;
q->Q=(int*)malloc(q->size*(sizeof(int)));
cout<<"queue created\n";
}

void enque(struct que*q)


{
int a;
if(q->rear==q->size-1)
{
cout<<"queue is full\n";
}
else
{
cout<<"enter value for queue\n";
cin>>a;
q->rear++;
q->Q[q->rear]=a;
cout<<"data is inserted under queue\n";
}
}

void display(struct que q)


{
int i;
for(i=q.front++;i<=q.rear;i++)
{
cout<<q.Q[i]<<"\n";
}
}

int main()
{
struct que q;
int ch,d;
do
{
cout<<"1.create\n 2.insert\n 3.display\n";
cout<<"enter your choice\n";
cin>>ch;
switch(ch)
{
case 1:
create(&q);
break;
case 2:
enque(&q);
break;
case 3:
display(q);
break;
default:
cout<<"invalid choice\n";
}
cout<<"do you want to used again, if yes press 1 othetwise 0\n";
cin>>d;
}
while(d==1);
return 0;
}
**>Queue using stack: logic bssically hum iske liye 2 stack ka used kerenge, ek
stack value for input lene ke liye
aur ek stack 1st wale stack ka value ko contain kerega value ko display kerwane ke
liye
eg:intput 1,2,3
stack 1: stack 2:st2.push(st1.top())
| | | |
| 3 | | 1 |
| 2 | | 2 |
| 1 | | 3 |
|_______| |_______|

code:
class MyQueue {
private:
stack<int>input, output;

public:
MyQueue() {

void push(int x) {
input.push(x);
}

int pop() {
int val = peek();
output.pop();
return val;
}

int peek() {
if( output.empty() ){
while( input.empty() != true ){
output.push(input.top());
input.pop();
}
}

return output.top();
}

bool empty() {
return input.empty() && output.empty();
}
};

***SLIDING window and TWO POINTER(when we see subarray /substring all question
belongs to string and array then we used sliding window)
it has two type
1.window size fixed:ye given hota h
2.variable size:- isme window size fix ni hoti h
iske unser hum ek formula used kerte h (j-i)+1, jisse ki ek window bn jye ga aur ye
formula celega until <k tk where k is the size of window and i=start and j= end
when (j-i)-1 ==k then j++ i++;

**maximum sum subarray of size 3


code:-
int sum;
int max=0;
while(j<size)
{
sum=sum+arr[j];
if((j-i)+1<k)
{
j++;
}
elseif((j-i)+1==k)
{
if(sum>max)
{
max=sum;
sum=sum-arr[i];// for maintaining a window size
i++;
j++;
}
}

**Longest Substring Without Repeating Characters


Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

1st code:
class Solution {
public int lengthOfLongestSubstring(String s) {
int r=0,l=s.length()-1;
int a=s.length();
int count=0;
if(s.equals(" ") ||a==1)
{
count=1;
}
else
{
while(r<l)
{
if(s.charAt(r)!=s.charAt(l))
{
count++;
r++;
l--;
}
else if(s.charAt(r)==s.charAt(l))
{
r++;
count=1;
}
}
}
return count;
}
}
but after some time some test cases faild
so, optimal approach

int longestUniqueSubsttr(String S){


HashSet<Character> set = new HashSet<>();
int max = 0;
int left = 0;
for(int r = 0; r < S.length() ; r++){
char ch = S.charAt(r);
while(set.contains(ch)){
set.remove(S.charAt(left));
left++;
}
set.add(ch);
int len = r-left+1;
max = Math.max(max,len);
}
return max;
}

*** HEAP
Q>Min Heap Implementation?
sol?
class minHeap {
public:

int *heap;
int heapsize;

minHeap(int c) {
heapsize=0;
heap=new int[c];
}

int extractMinElement() {
if(heapsize<1)return -1;
if(heapsize==1)
{
heapsize--;
return heap[0];
}
int ans=heap[0];
heapsize--;
heap[0]=heap[heapsize];
heap[heapsize]=0;
heapify(0);
return ans;
}

void deleteElement(int ind) {


if(ind<heapsize)
{
decreaseKey(ind);
extractMinElement();
}
}

void insert(int val) {


int ind=heapsize;
heapsize++;
heap[ind]=val;
while(ind>0)
{
if(heap[ind]<heap[parent(ind)])
{
swap(heap[ind],
heap[parent(ind)]);
ind=parent(ind);
}
else break;
}
}

//created sepearet fucn for just simplicity


void heapify(int ind)
{
int root=ind;
int l=lchild(ind);
int r=rchild(ind);

if(l<heapsize &&
heap[root]>heap[l])
root=l;
if(r<heapsize &&
heap[root]>heap[r])
root=r;
if(root!=ind)
{
swap(heap[ind],heap[roor]);
heapify(root);
}
}

void decreaseKey(int ind)


{
heap[ind]=INT_MIN;
while(ind>0)
{
if(heap[ind]<heap[parent(ind)])
{
swap(heap[ind],
heap[parent(ind)]);
ind=parent(ind);
}
else break;
}
}

int parent(int i)
{
return (i-1)/2;
}
int rchild(int i)
{
return 2*i+2;
}
int lchild(int i)
{
return 2*i+1;
}
};

OR

public class minheap


{
public:
int size;
int capacity;
int*heaparr;
minheap(int c)
{
int size=0;
heaparr=new int[c];
capacity=c;
}

void insert(int val)


{
if(size==capacity)return;
size++;
heaparr[size-1]=val;
for(int i=size-1;i!=0;heaparr[i]<heaparr(parent(i)))
{
swap(heaparr[i],heaparr(parent(i));
i=parent(i);
}
}

int ExtactMin()
{
if(size<0)return-1;
if(size==1)size--;return heaparr[0];
swap(heaparr[0],heaparr[size-1];
size--;
heapify(0);
return heaparr[0];
}
void heapify(int n)
{
int li=left(i);
int ri=right(i);
int root=n;
if(li<size && heaparr[li]<heaparr[root])
{
root=li;
}
if(ri<size&& heaparr[ri]<heaparr[root])
{
root=ri;
}
if(root!=n)
{
swap(heaparr[n],heaparr[root];
return heapify(root);
}
}
int parent(int i)
{
return (i-1)/2;
}
int left(int i)
{
return 2*i+1;
}
int right(int i)
{
return 2*i+2;
}
}

Q>Convert min hip to max heap?


code:
void heapify(vector<int>&arr,int i,int n)
{
//arr=array, i=no, n=size
int left=2*i+1;
int right=2*i+2;
int root=i;
if(left<n && arr[left]> arr[root])
{
root=left;
}
if(right<n && arr[right]>arr[root])
{
root=right;
}
if(root!=i)
{
swap(arr[root],arr[i]);
heapify(arr,root,n);
}
}
void convertMinToMaxHeap(vector<int> &arr, int N){
for(int i=(N-1)/2;i>=0;i--)
{
heapify(arr, i,N);
}
}
}

Q>Kth largest element in an array?


sol:hum normally sort kerke bhi ker shkte h but uska time complexity jyade ho jata
h, to hum priority queue used kerenge in min heap form.
concept:hum kth tk chalange aur max heap me se element ko delete(extract) kerte
jayange, ab jo humara top element hoga heap ka wo mere kth mar hoga.
code:
class Solution {
static int[] kthLargest(int k, int[] arr, int n) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
int ans[] = new int[n];
for(int i = 0 ; i < n ; i++){
if(pq.size() < k){
pq.add(arr[i]);
}
else{
// ans[i] = pq.peek();
if(pq.peek() < arr[i]){
pq.remove();
pq.add(arr[i]);
}
}
if(pq.size() < k)ans[i] = -1;
else ans[i] = pq.peek();
}
return ans;
}
};
Q>Replace elements by its rank in the array?
Input:
N = 6
arr = [20, 15, 26, 2, 98, 6]
Output:
4, 3, 5, 1, 6, 2
Explanation:
After sorting, array becomes {2,6,15,20,26,98}
Rank(2) = 1 (at index 0)
Rank(6) = 2 (at index 1)
Rank(15) = 3 (at index 2)
Rank(20) = 4 (at index 3) and so on..
logic: hum sbse phele array ko sort kerlenge, then usko map me store keer lenge
with their rank and just print ker denge
code:
class Solution {
static int[] replaceWithRank(int arr[], int N) {
// code here
int n = arr.length;
int ans[] = new int[n];
for(int i = 0; i < n; i++){
ans[i] = arr[i];
}

Arrays.sort(arr);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int k =0;
for(int i = 0; i < n; i++){
if(!map.containsKey(arr[i]))
map.put(arr[i], k++);
}

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


int temp = map.get(ans[i]);
ans[i] = temp+1;
}

return ans;

}
}

Q>Hands of Straights?
Input:
N = 9
groupSize = 3
hand[ ] = {1, 2, 3, 6, 2, 3, 4, 7, 8}
Output: true
Explanation:
Alice's hand can be rearranged as {1, 2, 3} , {2, 3, 4}, {6, 7, 8}. There are three
groups with size 3.
Each group has 3 consecutive cards.

N = 5
groupSize = 2
hand[ ] = {1, 2, 3, 4, 5}
Output: false

concept:isko solve kerne ke liye sbse phele hum array ko mean meap me bana lenge,
then 1st elemet ka double kerenge, agar uska double present hoga humare
list me to hum continue ker dente until ya to loop khatam ka ho jye, ya to false na
aa jye
code:
class Solution {
static boolean isStraightHand(int N, int groupSize, int hand[]) {
// code here
if(N%groupSize!=0)return false;
PriorityQueue<Integer> pq=new PriorityQueue<>();
for(int val: hand)
{
pq.add(val);
}
while(!pq.isEmpty())
{
int small=pq.poll();
for(int i=1;i<groupSize;i++)
{
if(pq.remove(small+i))continue;
else return false;
}
}
return true;
}
}

Q>Minimum Cost of ropes?


Input:
n = 4
arr[] = {4, 3, 2, 6}
Output:
29
Explanation:
We can connect the ropes in following ways.
1) First connect ropes of lengths 2 and 3.
Which makes the array {4, 5, 6}. Cost of
this operation 2+3 = 5.
2) Now connect ropes of lengths 4 and 5.
Which makes the array {9, 6}. Cost of
this operation 4+5 = 9.
3) Finally connect the two ropes and all
ropes have connected. Cost of this
operation 9+6 =15
Total cost for connecting all ropes is 5
+ 9 + 15 = 29. This is the optimized cost
for connecting ropes.

logic:-Array ko hum mean heap me bana lenge, then queue me push ker denge sare
element ko, now hum 2 storing value lenge
aur queue ke top aur top-1 ke deta ko usme store ker denge, then un dono ka sum
kerke usko wapus queue me push ker denge and
ek and variable me wo sum ko add kerte chale jayange, ye step tb tk repeat kerenge
jb tk humaara queue > 1 rehega.
code:
#include <bits/stdc++.h>
using namespace std;
class Solution
{
//Function to return the minimum cost of connecting the ropes.
long long minCost(long long arr[], long long n) {
// Your code here

priority_queue<long long,vector<long long>,greater<long long>>pq;


for(int i=0;i<n;i++)pq.push(arr[i]);
long long ans=0;
long long sum=0;
while(pq.size()>1)
{
long long no1=pq.top();
pq.pop();
long long no2=pq.top();
pq.pop();
sum=no1+no2;
pq.push(sum);
ans=ans+(sum);
}
return ans;
}
};

Q>Maximum Sum Combination?


Input:
N = 2
K = 2
A [ ] = {3, 2}
B [ ] = {1, 4}
Output: {7, 6}
Explanation:
7 -> (A : 3) + (B : 4)
6 -> (A : 2) + (B : 4)
logic:
*hum yaha pe priority queue and ek array list ka used kerenge.
*hum do no array me ek kerke ke jiska sum bara hoga usko queue me
dalte jayange aur check kerenge ki agar queue ka element wo less than
new sum se to hum queue ke element ko waha se pop kerke array list me dal denge
and aur mere ko K diya hua h ki kitne samay tk humko max elemet ko find kerna h
to hum ye upper wala kam uske under kerenge.
code:
class Solution {
static List<Integer> maxCombinations(int N, int K, int A[], int B[])
{
List<Integer> al=new ArrayList<>();
Arrays.sort(A);
Arrays.sort(B);
PriorityQueue<Integer> pq=new PriorityQueue<>();

for(int i=N-1;i>N-1-K;i--)
{
for(int j=N-1;j>N-1-K;j--)
{
int sum=A[i]+B[j];

if(pq.size()<K)
{
pq.add(sum);
}
else if(sum>pq.peek())
{
pq.poll();
pq.add(sum);
}
else
break;
}
}

while(pq.size()>0&K>0)
{
al.add(0,pq.poll());
}

return al;
}
}

Q>Find median in a stream?


Input:
N = 4
X[] = 5,15,1,3
Output:
5
10
5
4
Explanation:Flow in stream : 5, 15, 1, 3
5 goes to stream --> median 5 (5)
15 goes to stream --> median 10 (5,15)
1 goes to stream --> median 5 (5,15,1)
3 goes to stream --> median 4 (5,15,1 3)
logic:hum 2 queue create kerenge ek 1stqueue mera single element ko store kerke
rekhega and second queue pair ka data ko.
code:
class Solution
{

priority_queue<int>s;
priority_queue<int>,greater<int>g;
public static void insertHeap(int x)
{
// add your code here
if(s.size()==0)
{
s.push(x);
return;
}
if(s.size()>g.size())
{
if(x<s.top())
{
g.push(s.top());
s.pop();
s.push(x);
}
else
{
g.push(x);
}
}
else
{
if(x<s.top())
{
s.push(x);
}
else
{
g.push(x);
s.push(g.top());
g.pop();
}
}

public static double getMedian()


{

if(s.size()==g.size())
{
return(double)(s.top()+ g.top())/2.0;
}else {
return s.top();
}
}

**>Greedy Approach
1>Assign Cookies?
Input:
N = 3
M = 2
greed [ ] = {1, 2, 3}
sz [ ] = {1, 1}
Output: 1
Explanation:
You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make
the child whose greed factor is 1 content.
You need to return 1.
code:
class Solution {
static int maxChildren(int N,int M,int greed[], int sz[]) {
// code here
Arrays.sort(greed);
Arrays.sort(sz);
int i = 0;
for(int j=0;i<greed.length && j<sz.length;j++) {
if(greed[i]<=sz[j])
i++;
}
return i;
}
}

2>Fractional Knapsack:Basically jesa ki hum jante h ki 0/1 knapsack problem me hum


ya to pura jata h ya to ni jata
but fractional me half jaa shakta h
eg:
Weight=50;
int v[]={60,100};
int w[]={10,20};
now 1st element ate hi uska jo weight h wo w se subtract ho jata h, but agar mera
w bara ho jata h weight se tb hum ek formula
ka used kerenge, formula=(v[i]/w[i])*Weight.
N = 3, W = 50
value[] = {60,100,120}
weight[] = {10,20,30}
Output:
240.000000
Explanation:
Take the item with value 60 and weight 10, value 100 and weight 20 and split the
third item with value 120 and weight 30, to fit it into weight 20. so it becomes
(120/30)*20=80, so the total value becomes 60+100+80.0=240.0
Thus, total maximum value of item we can have is 240.00 from the given capacity of
sack.

code:
public static void main(String[] args) {
int W=50;
double ans=0;
double formula=0;
int v[]={60,100};
int w[]={10,20};
for(int i=0;i<w.length;i++)
{
if(w[i]<W)
{
ans=ans+v[i];
W=W-w[i];
}
else if(w[i]>W)
{
formula=(v[i]/w[i])*W;
ans=ans+formula;
}
}
System.out.println(ans);
}

3>Minimum number of Coins?


Input: N = 43
Output: 20 20 2 1
Explaination:
Minimum number of coins and notes needed
to make 43.
code:

class Solution{
static List<Integer> minPartition(int N)
{
// code here
List<Integer> ans = new ArrayList<>();
int money[] = {2000, 500,200,100,50,20,10,5,2,1};
int i=0;
while(N>0){
if(money[i] <= N){
ans.add(money[i]);
N-= money[i];
}
else{
i++;
}
}
return ans;
}

}
4>Lemonade Change
Input:
N = 5
bills [ ] = {5, 5, 5, 10, 20}
Output: True
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change we return true.
logic:
basically iska approach asa h ki hum 5 aur 10 ke note ko count kerenge, if x==5 h
to five++ ker denge, if x==10 h to ek five ko subtract ker denge
and 10 ka cout le lenge :- five-- ten++, now if x==20 ata h to to iss case me hum 2
type se change return ker shakte h, either 10 & 5 note both, and
only five note, so check if(x==20){if (ten>0) t--,five--} else if(temp<0){five-=3};
code:
int five=0,ten=0;
for(int i=0;i<N;i++)
{
int x=bills[i];
if(x==5)
five++;
else if(x==10)
{
five--;ten++;
}
else
{
if(x==20)
{
if(ten>0)
{
ten--;five--;
}
else
{
five-=3;
}
}
}
if(five<0)
return false;
}
return true;
}

5>N meetings in one room?


Input:
N = 6
start[] = {1,3,0,5,8,5}
end[] = {2,4,6,7,9,9}
Output:
4
Explanation:
Maximum four meetings can be held with
given start and end timings.
The meetings are - (1, 2),(3, 4), (5,7) and (8,9)
code:
public static int maxMeetings(int start[], int end[], int n)
{
// add your code here
// add your code here
int meetings[][]=new int[n][2];
for(int i=0;i<n;i++){
meetings[i][0]=start[i];
meetings[i][1]=end[i];
}
Arrays.sort(meetings,(x,y)->x[1]-y[1]);
int total=1,previousEndTime=meetings[0][1];
for(int i=1;i<n;i++){
if(meetings[i][0]>previousEndTime){
total++;
previousEndTime=meetings[i][1];
}
}
return total;
}

Q>Jump Game?
Input:
N = 6
A[] = {1, 2, 0, 3, 0, 0}
Output:
1
Explanation:
Jump 1 step from first index to
second index. Then jump 2 steps to reach
4th index, and now jump 2 steps to reach
the end.
code:
class Solution {
static int canReach(int[] A, int N) {
// code here
int maxi=A[0];
if(N==1)
{
return 1;
}
if(maxi==0)
{
return 0;
}
for(int i=0;i<N-1;i++)
{
maxi=Math.max(maxi-1,A[i]);
if(maxi==0)
{
return 0;
}
}
return 1;
}
};
Q>Insert Interval?
Input:
N = 5
intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]]
newEvent = [5,10]
Output: [[1,2], [3,10], [12,16]]
Explanation: Because the new interval [5,10]
overlaps with [3,5],[6,7],[8,10].

Logic ye h ki 1st case: agar 1st 2d array ka 2nd element chota hota h new
comming 2d array se to iska matlab ye h ki wo apne sahi format me h, to hum list me
1st wale ko add ker denge.
2nd case: agar mera jo new 2d comming array h uska 2nd element chota h 1st wala
2d array ke 1st wale element se to hum new array ko add kerenge list me, aur 1st
wale 2d array ko as a new bana denge.
3rd case: agar over lap ker reha ho to uss case me hum new 2d array ke 1st place
me current array aur new array ka jo 1 st elemet chota h usse rakh renge and 2nd
place me bara wala.

code:
List<int[]> ans=new ArrayList<>();

for(int[] i: intervals)
{
if(newInterval[1]<i[0])
{
ans.add(newInterval);
newInterval=i;
}
else if(newInterval[0]>i[1])
{
ans.add(i);
}
else
{
newInterval[0]=Math.min(i[0],newInterval[0]);
newInterval[1]=Math.max(i[1],newInterval[1]);

}
}
ans.add(newInterval);
return ans.toArray(new int[0][]);

****>Tree
-->Binary Tree representation in c++?
code:
#include<iostream>
using namespace std;
struct node
{
int info;
struct node*left;
struct node*right;
};

struct node* createnode()


{
struct node*temp;
int data;
temp=(struct node*)malloc(sizeof(struct node));
if(temp==NULL)
{
cout<<"unable to create a node\n";
exit(0);
}
else
{
cout<<"enter a value for node\n";
cin>>data;
temp->info=data;
temp->left=NULL;
temp->right=NULL;
}
cout<<"Value is inserted in a tree and the value is"<<data<<"\n";
return temp;
}

void inorder(struct node* root)


{
if(root!=NULL)
{
inorder(root->left);
cout<<root->info<<"\n";
inorder(root->right);
}
}
void preorder(struct node*root)
{
if(root!=NULL)
{
cout<<root->info<<"\n";
preorder(root->left);
preorder(root->right);
}
}
struct node*createnode();
void inorder(struct node*root);
void preorder(struct node*root);
int main()
{
struct node* root;
int ch,r;
do
{
cout<<"1 create\n 2.InsertLeft\n 3.InsertRight\n 4.inorder\n 5.preorder\n";
cout<<"enter your choice\n";
cin>>ch;
switch(ch)
{
case 1:
root=createnode();
break;
case 2:
root->left=createnode();
break;
case 3:
root->right=createnode();
break;
case 4:
inorder(root);
break;
case 5:
preorder(root);
break;
default:
cout<<"invalid choice\n";
}
cout<<"do you want to add again press 1 otherwise 0\n";
cin>>r;
}
while(r==1);
return 0;
}

or
class Solution{
public:

void create_tree(node* root0, vector<int> &vec){


//Your code goes here
root0->left=newNode(vec[1]);
root0->right=newNode(vec[2]);
root0->left->left=newNode(vec[3]);
root0->left->right=newNode(vec[4]);
root0->right->left=newNode(vec[5]);
root0->right->right=newNode(vec[6]);
}

};
-->Inorder Traversal
class Solution {
public:
vector<int>v; //should be outside the main function
// Function to return a list containing the inorder traversal of the tree.
vector<int> inOrder(Node* root) {
// Your code here
if(root!=NULL)
{
inOrder(root->left);
v.push_back(root->data);
inOrder(root->right);

}
return v;
}
};

-->Levelorder Traversal
iska logic ye h ki yaha pe hum queue ka used kerenge aur data ko store kerenge
code:
vertor<int>levelorder(Node*root)
{
vector<int>ans;
queue<Node*>q;
q.push(root)
if(root==NULL)
return ans;
while(!q.empty())
{
Node*temp=q.front();
q.pop();
ans.push_back(temp->info);
if(temp->left!=NULL)
q.push(temp->left)
if(temp->right!=NULL)
q.push(temp->right)
}
return ans;
}

-->postorder traversal using one stack


logic:same as level order traversing, just in the place of queue we used stack and
lastly we just reverse our vector
code:
class Solution{
public:
vector<int> postOrder(Node* node) {
// code here
stack<Node*> s;
vector<int> ans;
s.push(node);
while(!s.empty()){
Node* temp=s.top();
s.pop();
ans.push_back(temp->data);
if(temp->left)
s.push(temp->left);
if(temp->right)
s.push(temp->right);
}
reverse(ans.begin(),ans.end());
return ans;
}
};

-->Count total no of node int LL?


code:
int countt(struct node*root)
{
if(root == NULL){
return 0;
}
else{
return 1 + countt(root->left) + countt(root->right);
}
}

-->Height of Binary Tree?


Input:
1
/ \
2 3
Output: 2
Logic: hum sbse phele, recursively left sub tree ka height ko calculate ker lenge,
then same as right sum tree ka calculate ker lenge, aur undono me max find kerke +1
ker denge.
code:
int height(struct node*root)
{
int left=0,right=0;
int maxh=0;
if(root==NULL)
{
return 0;
}
else
{
left=height(root->left);
right=height(root->right);
}

return max(left,right)+1;//yaha pe +1 isliye ker rehe h kyu ki ek samay ke bd


jb recursive call root pe jye ga to waha pe vlaue 1 km ho jata h, to isko solve
kerne ke liye hum asa ker rehe h.
}

-->Diameter of a Binary Tree?


Basicalyy isme hume diameter find kerna h
formula: 1+height of left+height of right tree.
logic: basicalyy hum sare node ka height nikalange,aur per node ka diameter ko
calculate kerenge.
code:
class Solution {
public:

int res = 0;

int height(TreeNode* root){


if(root == NULL)
return 0;

int lh = height( root-> left);


int rh = height( root-> right);

res = max(res, 1+lh+rh);

return 1+ max(lh, rh);

int diameterOfBinaryTree(TreeNode* root) {


int data = height(root);
return res-1;
}
};

-->Determine if Two Trees are Identical?


Input:
1 1
/ \ /\
2 3 2 3
Output:
Yes
logic:Basicalyy hum left and right traverse ker lenge, 2no tree ka, then dono ke
root se ending tk data ko check ker lenge, agar data same hua to return true ni to
false
code:
class Solution
{
public:
//Function to check if two trees are identical.
bool isIdentical(Node *r1, Node *r2)
{
//Your Code here
if(r1 == NULL && r2 == NULL){
return true;
}

if(r1 == NULL && r2 != NULL){


return false;
}

if(r1 != NULL && r2 == NULL){


return false;
}

//simultaneously traverse both the tree


bool left = isIdentical(r1->left,r2->left);
bool right = isIdentical(r1->right,r2->right);

//checking if the data at each node of both the tree is same or not
bool value = (r1->data == r2->data);

if(left && right && value){


return true;
}
else{
return false;
}
}
};
another logic:
do level order traversal, check firstly both level is equal or not if not equal,
just return false, else now store the data of both
tree into a 2 queue, just compare top() of both queue, if both top() is equal then
pop(), if not equal just break the process and return
false, if at the end both queue is empty then just return true.

You might also like