Coding Question
Coding Question
A> Array.
OR
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;
}
}
}
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
OR
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);
}
}
}
}
}
}
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;
}
}
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;
}
}
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);
}
}
if(a[i]==b[i])
{
System.out.println("1");
break;
}
else
{
System.out.println("0");
break;
}
}
}
}
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;
}
}
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;
}
}
}
}
}
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");
}
}
}
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);
}
}
}
}
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");
}
}
}
}
}
}
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;
}
}
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";
}
}
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;
}
}
for(j=i+1;j<n.length;j++)
{
if(n[i]+1==n[j])
{
count++;
}
}
//System.out.println(n[i]);
}
//System.out.println(count);
}
}
or
// if index is even
if (i % 2 == 0) {
if (arr[i] < arr[i - 1]) {
// if index is odd
else {
if (arr[i] > arr[i - 1]) {
// Driver code
public static void main(String[] args)
{
int n = 5;
int arr[] = { 1, 3, 2, 2, 5 };
rearrange(arr, n);
}
}
}
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--;
}
}
}
// 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
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);
}
}
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]);
}
}
}
}
}
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]);
}
}
}
}
}
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);
}
}
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;
}
}
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;
}
};
so ba basically isko solve kerne ke liye hum transpose of matrix ka used kerenge
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");
}
}
}
int r = n-1;
while(l<=r){
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;
}
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);
}
}
}
}
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.
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;
}
}
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];
}
}
code:
class Solution
{
public static int findPages(int[]A,int N,int M)
{
if(N<M){
return -1;
}
int low=0;
int high=0;
if(A[i]>low){
low= A[i];
}
high+= A[i];
}
int res=-1;
while(low<=high){
return res;
}
int student=1;
int sum=0;
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--;
}
}
}
}
}
}
}
import java.util.*;
class Ns
{
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;
}
}
return false;
else
map.put(ch,ch2);
}
return true;
}
}
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));
}
}
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);
}
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;
}
};
if(S.equals(revStr)){
return 1;
}
else{
return 0;
}
}
};
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();
}
}
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);
}
}
}
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;
}
}
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);
}
}
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;
}
}
}
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);
}
}
}
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);
}
}
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;
}
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;
}
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;
}
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*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;
}
};
}
};
}
};
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;
}
->>>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;
}
bool found=false;
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
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");
}
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;
}
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;
};
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;
}
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;
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;
}
int size()
{
cout<<"Size of Stack is: "<<stacksize<<endl;
return stacksize;
}
int empty()
{
if(head==NULL)
{
cout<<"Stack is Empty!"<<endl;
return 1;
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() {
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;
}
return s.top();
}
int main()
{
return 0;
}
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;
}
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();
}
};
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.
};
**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.
code:
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
stack<int> st;
}
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);
}
};
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();
}
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;
};
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++;
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
*** 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;
}
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);
}
}
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
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;
}
}
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++);
}
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;
}
}
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
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;
}
}
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();
}
}
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;
}
}
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);
}
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;
}
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;
};
or
class Solution{
public:
};
-->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;
}
int res = 0;
//checking if the data at each node of both the tree is same or not
bool value = (r1->data == r2->data);