Posts

Showing posts from April, 2021

Sort 0 1 2

  You are given an integer array/list(ARR) of size N. It contains only 0s, 1s and 2s. Write a solution to sort this array/list in a 'single scan'. 'Single Scan' refers to iterating over the array/list just once or to put it in other words, you will be visiting each element in the array/list just once. Sample Input 1: 7 0 1 2 0 2 0 1 Sample Output 1: 0 0 0 1 1 2 2 import java.util.Scanner; public class Sort012 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } sort012(a); print(a); } public static void print(int a[]) { System.out.println("Updated Array -> "); for(int i=0;i<a.length;i++) { System.out.print(a[i]+" "); } } public static void sort012(int[] arr){ int l=arr.length; int zero=0; int one=0; for(int i=0;i<l;i++) { if(arr[i]==0) { zero++; } else if(a

Check Array Rotation

  You have been given an integer array/list(ARR) of size N. It has been sorted(in increasing order) and then rotated by some number 'K' in the right hand direction. Your task is to write a function that returns the value of 'K', that means, the index from which the array/list has been rotated. Sample Input 1: 6 5 6 1 2 3 4 Sample Output 1: 2 Approach 1 - package CodingNinjas; import java.util.Scanner; public class CheckRotation { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } int sl=arrayRotateCheck(a); System.out.println(sl); } public static int arrayRotateCheck(int[] arr) { int l=arr.length; int c=0; for(int i=0;i<l-1;i++) { if(arr[i]>arr[i+1]) { c=i+1; break; } } return c; } } Approach 2 - public class Solution { public static int arrayRotateCheck(int[] arr)

Second Largest Element

  You have been given a random integer array/list(ARR) of size N. You are required to find and return the second largest element present in the array/list. If N <= 1 or all the elements are same in the array/list then return -2147483648 or -2 ^ 31(It is the smallest value for the range of Integer) Sample Input 1: 7 2 55 77 88 4 8 99 Sample Output 1: 88 import java.util.Scanner; public class SecondLargest { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } int sl=secondLargestElement(a); System.out.println(sl); } public static int secondLargestElement(int[] arr) { int l=arr.length; int max=Integer.MIN_VALUE; int secLar=Integer.MIN_VALUE; for(int i=0;i<l;i++) { if(arr[i]>max) { secLar=max; max=arr[i]; } if(arr[i]<max && arr[i]>secLar) { secLar=arr[i

Rotate Array

  You have been given a random integer array/list(ARR) of size N. Write a function that rotates the given array/list by D elements(towards the left). Sample Input 1: 5 2 1 2 3 4 5 Sample Output 1: Updated Array -> 3 4 5 1 2 package CodingNinjas; import java.util.Scanner; public class RotateArray { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int d=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } rotate(a, d); print(a); } public static void print(int a[]) { System.out.println("Updated Array -> "); for(int i=0;i<a.length;i++) { System.out.print(a[i]+" "); } } public static void rotate(int[] arr, int d) { int l=arr.length; int t[]=new int[l]; int k=0; for(int i=0;i<d;i++) { t[i]=arr[i]; } for(int i=d;i<l;i++) { arr[i-d]=arr[i]; } for(int i=l-d;i<l;i++) { arr[i]=t[k++]; } } }

Push Zeroes To End

  You have been given a random integer array/list(ARR) of size N. You have been required to push all the zeros that are present in the array/list to the end of it. Also, make sure to maintain the relative order of the non-zero elements. Sample Input 1: 6 2 0 0 2 3 0 Sample Output 1: Updated Array -> 2 2 3 0 0 0 import java.util.Scanner; public class PushZeros { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } pushZerosAtEnd(a); print(a); } public static void print(int a[]) { System.out.println("Updated Array -> "); for(int i=0;i<a.length;i++) { System.out.print(a[i]+" "); } } public static void pushZerosAtEnd(int[] arr) { int l = arr.length; int k=0; for(int i=0;i<l;i++) { if(arr[i]!=0) { arr[k]=arr[i]; k++; } } while(k<l) { arr[k]=0; k++; } } }

Merge Two Sorted Arrays

  You have been given two sorted arrays/lists(ARR1 and ARR2) of size N and M respectively, merge them into a third array/list such that the third array is also sorted. Sample Input 1 : 3 1 3 6 4 2 7 8 9 Sample Output 1 : Merged Array -> 1 2 3 6 7 8 9 import java.util.Scanner; public class MergeSortedArray { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } int m=s.nextInt(); int b[]=new int[m]; for(int i=0;i<m;i++) { b[i]=s.nextInt(); } int c[]=merge(a, b); print(c); } public static void print(int a[]) { System.out.println("Merged Array -> "); for(int i=0;i<a.length;i++) { System.out.print(a[i]+" "); } } public static int[] merge(int arr1[], int arr2[]) { int l1=arr1.length; int l2=arr2.length; int l=l1+l2; int arr3[]=new int[l]; int k=0; int i=0; int j=

Insertion Sort

  Sample Input 1: 5 4 3 8 2 9 Sample Output 1: Sorted Array -> 2 3 4 8 9 import java.util.Scanner; public class InsertionSort { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } insertionSort(a); print(a); } public static void print(int a[]) { System.out.println("Sorted Array -> "); for(int i=0;i<a.length;i++) { System.out.print(a[i]+" "); } } public static void insertionSort(int[] arr) { int l=arr.length; //Considering 0th element will be in sorted for(int i=1;i<l;i++) { int j=i-1; int t=arr[i]; while(j>=0 && arr[j]>t) { arr[j+1]=arr[j]; j--; } arr[j+1]=t; } } }

Selection Sort

  Sample Input 1: 5 1 5 3 2 6 Sample Output 1: Sorted Array -> 1 2 3 5 6 import java.util.Scanner; public class SelectionSort { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } selectionSort(a); print(a); } public static void print(int a[]) { System.out.println("Sorted Array -> "); for(int i=0;i<a.length;i++) { System.out.print(a[i]+" "); } } public static void selectionSort(int[] arr) { int l=arr.length; for(int i=0;i<l-1;i++) { int min=Integer.MAX_VALUE; int minIndex=-1; int t=0; for(int j=i;j<l;j++) { if(arr[j]<min) { min=arr[j]; minIndex=j; } } t=arr[minIndex]; arr[minIndex]=arr[i]; arr[i]=t; } } }

Bubble Sort

  Sample Input 1: 4 2 3 1 4 Sample Output 1: Sorted Array -> 1 2 3 4 import java.util.Scanner; public class BubbleSort { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } bubbleSort(a); print(a); } public static void print(int a[]) { System.out.println("Sorted Array -> "); for(int i=0;i<a.length;i++) { System.out.print(a[i]+" "); } } public static void bubbleSort(int[] a){ int l=a.length; for(int i=0;i<l-1;i++) { for(int j=0;j<l-i-1;j++) { if(a[j]>a[j+1]) { int t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } } }

Binary Search

  Sample Input 1: 5 2 1 2 3 4 5 Sample Output 1: 1 import java.util.Scanner; public class BinarySearch { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int x=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } int ab=binarySearch(a, x); System.out.println(ab); } public static int binarySearch(int[] arr, int x) { int l=0; int e=arr.length-1; while(l<=e) { int m=(l+e)/2; if(arr[m]==x) { return m; } else if(arr[m]>x) { e=m-1; } else { l=m+1; } } return -1; } }

Compress the String

  Write a program to do basic string compression. For a character which is consecutively repeated more than once, replace consecutive duplicate occurrences with the count of repetitions. Sample Input 1: aaabbccdsa Sample Output 1: a3b2c2dsa import java.util.Scanner; public class CompressString { public static void main(String[] args) { Scanner s = new Scanner(System.in); String st = s.nextLine(); String c = getCompressedString(st); System.out.println(c); } public static String getCompressedString(String str) { String s=""; int l=str.length(); for(int i=0;i<l;i++) { // Count occurrences of current character int count = 1; while (i < l - 1 && str.charAt(i) == str.charAt(i + 1)) { count++; i++; } if (count == 1) { s=s+str.charAt(i); } else { s=s+str.charAt(i)+count; } } return s; } }

Highest Occuring Character

  For a given a string(str), find and return the highest occurring character. Sample Input 1: abdefgbabfba Sample Output 1: b Approach 1 - import java.util.Scanner; public class HighestOccurence { public static void main(String[] args) { Scanner s = new Scanner(System.in); String st = s.nextLine(); char c = highestOccuringChar(st); System.out.println(c); } public static char highestOccuringChar(String str) { char chh=' '; int max=0; int l=str.length(); for(int i=97;i<=122;i++) { int c=0; char ch1=(char)i; for(int j=0;j<l;j++) { char ch=str.charAt(j); if(ch1==ch) { c++; } } if(c>max) { max=c; chh=ch1; } } return chh; } } Approach 2 - public class Solution { public static char highestOccuringChar(String str) {           int N = 256; int ctr[] = new int[N]; int l = str.length(); for (int i = 0; i < l; i++) ctr[str.charAt(i)]++; int max = -1; char result =

Remove character

  For a given a string(str) and a character X, write a function to remove all the occurrences of X from the given string. Sample Input 1: aabccbaa a Sample Output 1: bccb public class Solution { public static String removeAllOccurrencesOfChar(String str, char ch) { int l=str.length(); String s=""; for(int i=0;i<l;i++) { char c = str.charAt(i); if(ch!=c) { s=s+c; } } return s; } }

Reverse Each Word

  The task is to implement a function so as to print the sentence such that each word in the sentence is reversed. Sample Input 1: Always indent your code Sample Output 1: syawlA tnedni ruoy edoc public class Solution { public static String reverseEachWord(String str) { str=str+ " "; int l=str.length(); String s=""; String p=""; for(int i=0;i<l;i++) { char ch=str.charAt(i); if(ch!=' ') { p=ch+p; } else { s=s+p+" "; p=""; } } return s; } }

Remove Consecutive Duplicates

  For a given string(str), remove all the consecutive duplicate characters. Sample Input 1: aabccbaa Sample Output 1: abcba public class Solution { public static String removeConsecutiveDuplicates(String str) { str=str+" "; int l=str.length(); String s=""; for(int i=0;i<l-1;i++) { char ch1=str.charAt(i); char ch2=str.charAt(i+1); if(ch1!=ch2) { s=s+ch1; } } return s; } }

Check Permutation

  For a given two strings, 'str1' and 'str2', check whether they are a permutation of each other or not. Sample Input 1: abcde baedc Sample Output 1: true Approach 1- (Time limit might exceed in some test cases) public class Solution { public static boolean isPermutation(String str1, String str2) { int n=str1.length(); int l=str2.length(); int c=0; if(n!=l) return false; for(int i=0;i<n;i++) { for(int j=0;j<l;j++) { if(str1.charAt(i)==str2.charAt(j)) { c++; }} } if(c==n) { return true; } return false; }} Approach 2 - import java.util.Arrays; public class Solution { public static boolean isPermutation(String str1, String str2) { int n=str1.length(); int l=str2.length();                if(n!=l) return false; char a[]= str1.toCharArray(); char b[]= str2.toCharArray(); Arrays.sort(a); Arrays.sort(b);

Reverse String Wordwise

  Reverse the given string word wise. That is, the last word in given string should come at 1st place, last second word at 2nd place and so on. Individual words should remain as it is. Sample Input 2: god is one Sample Output 2: one is god Approach 1 - import java.util.Scanner; public class ReverseWordwise { public static void main(String[] args) { Scanner s = new Scanner(System.in); String st = s.nextLine(); String str = reverseWordWise(st); System.out.println(str); } public static String reverseWordWise(String input) { String s=""; input=" " + input; String str[]=input.split(" "); for(int i=str.length-1;i>0;i--) { s=s+ str[i]+ " "; } return s; } } Approach 2 - public class Solution { public static String reverseWordWise(String input) { String x=""; int sp=input.length(); for(int i=input.length()-1;i>=0;i--) { if(i==0) { x=x+input.substring(0,sp); }

All Substrings

  For a given input string(str), write a function to print all the possible substrings. Sample Input 1: abc Sample Output 1: a ab abc b bc c import java.util.Scanner; public class AllSubstring { public static void main(String[] args) { Scanner s = new Scanner(System.in); String st = s.nextLine(); printSubstrings(st); } public static void printSubstrings(String str) {                     int l=str.length(); for(int i=0;i<l-1;i++) { for(int j=i;j<l;j++) { System.out.println(str.substring(i,j+1)); } } System.out.println(str.substring(l-1)); } }          

String Palindrome

  Given a string, determine if it is a palindrome, considering only alphanumeric characters. Sample Input 1 : abcdcba Sample Output 1 : true public class Solution { public static boolean isPalindrome(String str) { int l =str.length(); String r=""; for(int i=0;i<l;i++) { char ch=str.charAt(i); r=ch+r; } if(r.equals(str)) { return true; } return false; } }

Count Words

  For a given input string(str), find and return the total number of words present in it. Sample Input 1: this is a sample string Sample Output 1: 5 public class Solution { public static int countWords(String str) { //Your code goes here int l=str.length(); int c=0; str=" "+str; for(int i=0;i<l;i++) { char ch=str.charAt(i); if(ch==' ') { c++; } } return c; } }

Spiral Matrix

  For a given two-dimensional integer array/list of size (N x M), print it in a spiral form. That is, you need to print in the order followed for every iteration: a. First row(left to right) b. Last column(top to bottom) c. Last row(right to left) d. First column(bottom to top) Sample Input 1: 4 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Sample Output 1: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 import java.util.Scanner; public class SpiralMatrix { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int m = s.nextInt(); int input[][] = new int[n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { input[i][j] = s.nextInt(); } } spiralPrint(input); } public static void spiralPrint(int matrix[][]){ int rs= 0; int cs= 0; int re= matrix.length-1; int ce= matrix[0].length-1; int total = matrix.length * matrix.length; int c= 0; while(c<total) { for(int i=cs;i<=ce;i++)

Print Like a Wave

  For a given two-dimensional integer array/list of size (N x M), print the array/list in a sine wave order, i.e, print the first column top to bottom, next column bottom to top and so on. Sample Input 1: 3 4 1 2 3 4 5 6 7 8 9 10 11 12 Sample Output 1: 1 5 9 10 6 2 3 7 11 12 8 4 import java.util.Scanner; public class WaveArray { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int m = s.nextInt(); int input[][] = new int[n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { input[i][j] = s.nextInt(); } } wavePrint(input); } public static void wavePrint(int mat[][]){ if(mat.length==0) { return; } for(int i=0;i<mat[0].length;i++) { if(i%2==0) { for(int j=0;j<mat.length;j++) { System.out.print(mat[j][i]+ " "); } } else { for(int j=mat.length-1;j>=0;j--) { System.out.pri

Total Sum on the Boundaries and Diagonals

  For a given two-dimensional square matrix of size (N x N). Find the total sum of elements on both the diagonals and at all the four boundaries. Sample input 1: 3 3 1 2 3 4 5 6 7 8 9 Sample Output 1: 45 import java.util.Scanner; public class SumDiaBound { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int m = s.nextInt(); int input[][] = new int[n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { input[i][j] = s.nextInt(); } } totalSum(input); } public static void totalSum(int[][] mat) { int s=0; for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[i].length;j++) { if(i==j || i+j==mat.length-1) { s=s+mat[i][j]; } else if(i==0 || i==mat.length-1 || j==0 || j==mat.length-1) { s=s+mat[i][j]; } } } System.out.println(s); } }

Largest Row or Column

  For a given two-dimensional integer array/list of size (N x M), you need to find out which row or column has the largest sum(sum of all the elements in a row/column) amongst all the rows and columns. If there doesn't exist a sum at all then print "row 0 -2147483648", where -2147483648 or -2^31 is the smallest value for the range of Integer. Sample Input 1 : 1 2 2 1 1 1 1 Sample Output 1 : row 0 2 import java.util.Scanner; public class LargestRowOrCol { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int m = s.nextInt(); int input[][] = new int[n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { input[i][j] = s.nextInt(); } } findLargest(input); } public static void findLargest(int mat[][]){ int maxR=Integer.MIN_VALUE; int maxIndexR=Integer.MIN_VALUE; int maxIndexC=Integer.MIN_VALUE; int maxC=Integer.MIN_VALUE; //int l=mat.length; if(mat.lengt

Leaders in array

  Given an integer array A of size n. Find and print all the leaders present in the input array. An array element A[i] is called Leader, if all the elements following it (i.e. present at its right) are less than or equal to A[i]. Print all the leader elements separated by space and in the same order they are present in the input array. Sample Input 1 : 6 3 12 34 2 0 -1 Sample Output 1 : 34 2 0 -1 import java.util.Scanner; public class LeaderArray { public static void main(String[] args)  { // int input[]= {1, 4, 9, 5, 3, 2, 0}; //int input[]= {13,17,5,4,6}; // leaders(input); // //public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int input[] = new int[n]; for(int i = 0; i < n; i++) { input[i] = s.nextInt(); } leaders(input); } // public static void leaders(int[] input) { int l=input.length; for(int i=0;i<l;i++) { boolean isDec=true; for(int j=i+1;j<l;

Minimum Length Word

  Given a string S (that can contain multiple words), you need to find the word which has minimum length. Sample Input 1 : this is test string Sample Output 1 : is public class Solution { public static String minLengthWord(String input){ String[] arr=input.split(" "); int i=0; int minlength; minlength=Integer.MAX_VALUE; String smallest; smallest = ""; for(i=0;i<arr.length;i++) { if(arr[i].length() < minlength) { smallest=arr[i]; minlength=arr[i].length(); } } return smallest; } }

Print 2D array

  Given a 2D integer array with n rows and m columns. Print the 0th row from input n times, 1st row n-1 times…..(n-1)th row will be printed 1 time. Sample Input : 3 3 1 2 3 4 5 6 7 8 9 Sample Output : 1 2 3 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 public class solution { public static void print2DArray(int input[][]) { for(int i=0;i<input.length;i++) { for(int k=0;k<(input.length-i);k++) { for(int j=0;j<input[i].length;j++) { System.out.print(input[i][j]+" "); } System.out.println(); } } } }