Minimum deletions required to make frequency of each letter unique in a String in Java

Minimum deletions to make frequency of each character unique


This is a popular interview question asked in Tier-1 companies.

Given a string, find the minimum number of characters to be deleted in a string so that the frequency of each character in the string is unique.

Question 1:
String s = 'aaaabbbcccdddd'
Frequency of characters : { a=4, b=3, c=3, d=4 }

a nd d both have same frequency 4, similarly b and c have same frequency 3. so frequency is repeated and we need to make it unique.
we need to delete three character from a, one characters from b to make their frequency different.
s = 'abbcccdddd'

Frequency of characters : { a=1, b=2, c=3, d=4 }

Detailed Description:
we need to make the frequency unique,
Either we need to delete one character from a or d so that we break the same frequency.
so we delete a, now string is "aaabbbcccdddd"

Now the frequency of a is 3, b is 3, c is 3 and d is 4
the frequency of a, b and c is repeating, we need to delete one character from a,
s = 'aabbbcccdddd'

Now the frequency of a is 2, b is 3, c is 3 and d is 4
the frequency of b and c is repeating, we need to delete one character from b, but this will make b count to 2 which will be same as a count, so we will delete 2 characters from b so the frequency will be 1.
s = 'aabcccdddd'

Now the frequency of a is 2, b is 1, c is 3 and d is 4, so is unique now.

Answer is 4 because we delete 4 characters to make the frequency unique.

Java Program to find minimum deletions in a String to make the frequency of each character unique


package javabypatel;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class MinimumDeletionUsingPriorityQueue {
    public static void main(String[] args) {
        System.out.println(countFrequency("aaaabbbcccdddd"));
    }

    private static int countFrequency(String str) {

        if (str == null || str.length() < 2) {
            return 0;
        }

        //Taking a map to find unique occurrence of each character in a string.
        Map<Character, Integer> frequencyCount = new HashMap<>();
        for (char ch: str.toCharArray()) {
            int count = frequencyCount.getOrDefault(ch, 0);
            frequencyCount.put(ch, count + 1);
        }

        //Taking a PriorityQueue for processing the count of each occurrence of a character
        //Putting the values in reverse order so that higher counts are at head
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());

        //dumping the frequency of each characters in a Priority queue.
        for (Map.Entry<Character, Integer> entry : frequencyCount.entrySet()) {
            priorityQueue.add(entry.getValue());
        }

        int deletionCount = 0;

        while (!priorityQueue.isEmpty()) {
            int frequency = priorityQueue.poll();

            //If there is no element left after poll, It means we are done, return deletionCount.
            if (priorityQueue.size() == 0 ) {
                return deletionCount;
            }

            //Here we are comparing the polled count with the count at the head. since our PriorityQueue is in reverse order
            //Counts that are same will be grouped together. So idea is to check polled and peek and if they are same it means we
            //need to delete one occurrence of a character to make it unique, but the catch is after deletion, the count which we encountered
            //may also be the occurrence count of other character present in a queue, so we have to repeat this process.
            //number of time we delete the occurrence, we add that in our deletionCount.
            if (frequency == priorityQueue.peek()) {
                //it means we have to delete one character to make the frequency unique
                priorityQueue.add(frequency-1);

                //Number of time we delete the character to make frequency unique, we have to increase the deletionCount.
                deletionCount ++;
            }
        }
        return deletionCount;
    }
}

Find longest length bi-valued slice in an array

Find longest length bi-valued slice in an array in java


This is a popular interview question asked in Tier-1 companies.

You are given a sequence of n integers and the task is to find the maximum slice of the array which contains no more than two different numbers.

Example:
1. Input: [1, 2, 1, 2, 2, 3, 3, 2, 3]
Output: 6
Max slice is [2, 2, 3, 3, 2, 3] which contains only two numbers 2 and 3 and the length is 6 

2. Input: [1, 2, 3]
Output: 2
Max slice is either [1, 2] or [2, 3] which contains only two numbers and the length is 2

3. Input: [1, 4, 4, 1, 4]
Output: 5 
Max slice is whole array which contains only two numbers 1 and 4 and the length is 5

4. Input: [2]
Output: 1 
Max slice is whole array which contains only one number 2 and the length is 1

Algorithm


As we are looking for bi-value slice, we will keep two pointer lastSeen and secondLastSeen which keep track of the numbers we last read.

So if the current number we are reading is one of the number we read before that is it is same as either lastSeen or secondLastSeen, then we can increase our longest bi-value slice counter(say tempCounter) by 1

So we have three variables till now, lastSeen, secondLastSeen and tempCounter to store the current longest bi-value slice.


Consider the array [121223323]

say we read 1212and we were good at that point, now we read element 3, so in that case new series has started but including the current number 3 we can include the previous two 2's in this series that is starting from index 3.

So instead of going back and see the last repeated number, we will keep track of this in the separate variable lastSeenNumberRepeatedCount which holds the number of times last seen value repeated in this case lastSeenNumberRepeatedCount would be 2, because when we encountered 3 at index 5, the number before 3 is 2 which first occur at index 3 and then the same number repeated that is lastSeen number repeated at index 4 so making lastSeenNumberRepeatedCount to 2.

So when we encounter 3 at index 5, we directly add the lastSeenNumberRepeatedCount to our tempCounter so it would be lastSeenNumberRepeatedCount + 1 (added 1 because starting from 3 new series has started, so including the current number 3)

So we have four variables till now, lastSeen, secondLastSeen, tempCounter and lastSeenNumberRepeatedCount.

We also need one more variable for storing our longest bi-valued slice as tempCounter will change when new series starts so what about the previous value of tempCounter which was our last longest bi-value slice till that point.

So we have five variables till now, lastSeen, secondLastSeen, tempCounter, lastSeenNumberRepeatedCount and lbs for storing result.

Java Program to find largest bi-valued slice in an array


package javabypatel;

public class LongestBiValueSlice {
    public static void main(String[] args) {
        System.out.println(new LongestBiValueSlice().getLongestSlice(new int[]{2}));
    }

    public int getLongestSlice(int[] arr) {
        int lastSeen = -1;
        int secondLastSeen = -1;
        int lbs = 0;
        int tempCount = 0;
        int lastSeenNumberRepeatedCount = 0;

        for (int current : arr) {
            if (current == lastSeen || current == secondLastSeen) {
                tempCount ++;
            } else {
                // if the current number is not in our read list it means new series has started, tempCounter value in this case will be
                // how many times lastSeen number repeated before this new number encountered + 1 for current number.
                tempCount = lastSeenNumberRepeatedCount + 1;
            }

            if (current == lastSeen) {
                lastSeenNumberRepeatedCount++;
            } else {
                lastSeenNumberRepeatedCount = 1;

                secondLastSeen = lastSeen;
                lastSeen = current;
            }

            lbs = Math.max(tempCount, lbs);
        }
        return lbs;
    }
}

Check if an array is sorted in Java - Iterative and Recursive approach

Check if an array is sorted in Java - Iterative and Recursive approach.


Given an array, check if it is already sorted or not using both Iterative and Recursive way.

Lets see sample input and output for better understanding:
Check whether the array is sorted in Java
Check whether array is sorted or not

Search element In Sorted Rotated Array in Java

Search the element In Sorted Rotated Array in Java.


Given an array which is sorted in ascending order and is rotated, say for example
Example: original array [1,2,3,4,5,6,7] might become [3,4,5,6,7,1,2]
You are given a key to search. If key is found in the array return its index, otherwise return -1.

Note: You may assume no duplicate exists in the array, find an element in the rotated array in
O(log n) time.

Lets see sample input and output:

Find Container with Most Water in Java

Find Container with Most Water.


Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You cannot slant the container.

Lets understand what is the input and the expected output.

Maximum consecutive one’s in a binary array

Find the maximum consecutive 1's in an array of 0's and 1's. And Find length of the longest consecutive One's in binary representation.


Given a binary array, find the maximum number of consecutive 1s in this array or find the maximum consecutive 1's in an array of 0's and 1's.

Lets understand what is the input and the expected output.

Find element in a sorted array whose frequency is greater than or equal to n/2.

Find Majority Element in a Sorted Array in Java? OR Find element in a sorted array whose frequency is greater than or equal to n/2.


Given a sorted array, find the number in array that appears more than or equal to n/2 times.
Condition: there will always be element which is repeated more than n/2 times.

Lets understand with the help of example below,

Try to solve the problem in less than O(1) complexity.

Algorithm

If the element is sorted and such element is always present which is repeated more than n/2 times in that case the repeated element must be the middle element of the array.

If the most repeated element is starting from 0th index, in that case it has to stretch till middle index then only it will be repeated n/2 times,

If the most repeated element is present at last index, if that is the case than middle index should also contain the same element than only it would have be repeated n/2 times,

If the most repeated starts some where in the middle in this case it is sure it would be passing from the middle index for having its count greater than or equal to n/2 times.


package com.javabypatel.arrays;

public class MajorityOfElementInSortedArray {

    public static void main(String args[]) {
        int arr[] = { 1, 2, 3, 3 };
        int n = arr.length;
        System.out.println(findMajorityElement(arr, n));
    }
    public static int findMajorityElement(int arr[], int n) {
        return arr[n / 2];
    }
}

You may also like to see


Advanced Java Multithreading Interview Questions & Answers

Type Casting Interview Questions and Answers In Java?

Exception Handling Interview Question-Answer

Method Overloading - Method Hiding Interview Question-Answer

How is ambiguous overloaded method call resolved in java?

Method Overriding rules in Java

Interface interview questions and answers in Java


Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Check Majority Element in a Sorted Array in Java.

Majority Element in a Sorted Array in Java?


Given a sorted array, we need to find if a given x is a majority element.

What is Majority element: Number occurring more than half the size of the array is called Majority element.

Lets understand with the help of example below,
Try to solve the problem in less than O(N) complexity.

Algorithm


We will see two solutions one having time complexity O(N) and one using Binary Search approach having time complexity O(log N).

As the array is sorted we can use binary search to find the index of first occurrence of element to search and once that is found, we can directly add n/2 in that index to see if that index also contains the same element as element to search and if yes, then we have majority element else not.
package com.javabypatel.arrays;

public class MajorityOfElementInSortedArray {
    public static void main(String[] args) {

        int arr[];

        //arr = new int[] {1, 2, 2, 2, 3, 3, 3};
        //arr = new int[] {1, 1, 1, 2, 2, 3};
        //arr = new int[] {1, 1, 1, 2, 2, 2, 2};
        //arr = new int[] {2, 2};
        arr = new int[] {2};

        int x = 3;
        boolean result = isMajority(x, arr, arr.length);
        System.out.println(result);

        result = isMajorityUsingBinarySearch(x, arr, arr.length);
        System.out.println(result);
    }

    //Time complexity O(N)
    private static boolean isMajority(int elementToSearch, int[] arr, int length) {

        //Here we are calculating till what index we need to search for element.
        //we need to only search till length/2 index for even length array and length/2+1 for odd length array after that index if element is present/absent
        //doesn't matter as count of the element would not be greater than length/2+1 after crossing middle element.
        int searchUptil = length % 2 == 0 ? length / 2 : length / 2 + 1;

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

            //If we get the index of the first match elementToSearch then check the value at the (currentIndex + length/2)
            //if the value at that index is elementToSearch then elementToSearch occur more than length/2 times.
            if(arr[i] == elementToSearch && arr[i + arr.length/2] == elementToSearch) {
                return true;
            }
        }

        return false;
    }

    private static boolean isMajorityUsingBinarySearch(int elementToSearch, int[] arr, int length) {
        return isMajorityHelper(elementToSearch, arr, 0, length-1);

    }

    /*
        In this approach we will find the first instance of the elementToSearch using BinarySearch after that
        we will directly check the index n/2 from that point and if it is same as elementToSearch then we have
        n/2 count of elementToSearch else not.
     */
    static boolean isMajorityHelper(int elementToSearch, int[] arr, int start, int end) {
        if (start > end) {
            return false;
        }

        int mid = start + (end - start) / 2;

        if (arr[mid] == elementToSearch && (mid == 0 || arr[mid-1] < elementToSearch)) {

            //If we get the index of the first match elementToSearch then check the value at the (currentIndex + length/2)
            //if the value at that index is elementToSearch then elementToSearch occur more than length/2 times.
            if((mid + arr.length/2 < arr.length) && arr[mid + arr.length/2] == elementToSearch) {
                return true;
            }

            return false;

        } else if (arr[mid] < elementToSearch) {
            //Search on right side of mid.
            return isMajorityHelper(elementToSearch, arr, mid + 1, end);
        } else {
            //if the elementToSearch is found and is not the first instance or
            //if elementToSearch is greater than mid, continue searching on left side of mid.
            return isMajorityHelper(elementToSearch, arr, start, mid - 1);
        }
    }


}

You may also like to see


Advanced Java Multithreading Interview Questions & Answers

Type Casting Interview Questions and Answers In Java?

Exception Handling Interview Question-Answer

Method Overloading - Method Hiding Interview Question-Answer

How is ambiguous overloaded method call resolved in java?

Method Overriding rules in Java

Interface interview questions and answers in Java


Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Merge sort explanation in java

Merge sort Algorithm in java.


Given a unsorted array, Sort it using Merge Sort Algorithm.

Lets understand what is the input and the expected output.

sort array using merge sort in java
Sort array using merge sort in java

Merge sort Algorithm


How Merge Sort works
  1. Merge Sort works by breaking the array into 2 equal parts say Left half and Right half.
  2. Again break 2 sub array that we got in Step 1 in two equal parts each.  
  3. Repeat above steps until only 1 element remains in array because array with only one element is always sorted. 
  4. So in each step we are breaking the array in Left half and Right half.  
  5. When complete array is divided and contains only Single element in Left and Right half each, Start comparing and sort each Left and Right half, So that portion of array will be sorted.
  6. Repeat Step 5 for all the remaining Left and Right sub-array and complete array will be sorted.

Merge sort Time complexity


Merge sort time complexity is O(N log N).

Lets understand with the help of below example.

merge sort algorithm with example
Merge sort algorithm with example

Java program to sort an array using merge sort


package com.javabypatel;

public class MergeSort {

    public static void main(String[] args) {
        int arr[] = {10, 1, -2, 8, 9, 10, 1};

        //Before sort
        print(arr);

        mergeSort(arr, 0, arr.length - 1);

        //After sort
        print(arr);
    }

    static void mergeSort(int arr[], int start, int end) {
        if (start >= end)
            return;

        int mid = start + (end - start) / 2;
        mergeSort(arr, start, mid);
        mergeSort(arr, mid + 1, end);
        merge(arr, start, mid, end);
    }

    static void merge(int[] arr, int start, int mid, int end) {
        int i = start;
        int j = mid + 1;
        int counter = 0;

        int[] tempArr = new int[(end - start) + 1];

        while (i <= mid && j <= end) {
            if (arr[j] < arr[i]) {
                tempArr[counter] = arr[j];
                j++;
            } else {
                tempArr[counter] = arr[i];
                i++;
            }
            counter++;
        }
        while (i <= mid) {
            tempArr[counter] = arr[i];
            i++;
            counter++;
        }

        while (j <= end) {
            tempArr[counter] = arr[j];
            j++;
            counter++;
        }

        for (int k = 0; k < counter; k++) {
            arr[start + k] = tempArr[k];
        }
    }

    static void print(int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}

You may also like to see


Sort Linked list using Merge sort

Bubble Sort

Heap Sort

Selection Sort

Insertion Sort


How ConcurrentHashMap works and ConcurrentHashMap interview questions

How Much Water Can A Bar Graph with different heights can Hold

Interview Questions-Answer Bank

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Java Program for Linear Search.

Java Program for Linear Search.

Linear search is a searching algorithm which sequentially searches element in an array.

In this algorithm, elements of array is scanned one by one and check if it is matching with element to search and if found return true else return false.

In last post, we saw how to do Binary search: Binary Search in Java. In this post, we will focus on linear serach.

Lets understand the problem statement graphically and it will be more clear,  



Linear Search Algorithm in Java

Linear Search Algorithm in Java OR
Sequential Search Algorithm in Java

Linear search is a searching algorithm which sequentially searches element in an array.

In this algorithm, elements of array is scanned one by one and check if it is matching with element to search and if found return true else return false.

Lets understand the problem statement graphically and it will be more clear,  



How Binary search Algorithm works in Java

How Binary search Algorithm works in Java.

Binary search is a technique for searching an element from sorted array.

Let's understand Binary Search Algorithm with the help of an example, 
You will be given a sorted array and an element, find whether element is present in array or not.
 

Binary Search in Java

Binary Search in Java.

Binary search is a technique for searching an element from sorted array.

Let's understand Binary Search with the help of an example,
You will be given a sorted array and an element, find whether element is present in array or not.
Lets understand the problem statement graphically and it will be more clear,  
 

Find element in a sorted array

Binary Search in Sorted Array OR
Given a sorted array, Search a given element in array.


Searching an element in a sorted array.
You will be given a sorted array and an element, you need to find whether element is present in array or not.

Lets understand the problem statement graphically and it will be more clear,  
 

Kadane's Algorithm in Java.

Kadane's Algorithm in Java to find Largest Sum Contiguous Subarray.

Kadane's Algorithm in Java. Kadane's Algorithm to solve maximum sum subarray problem.

The maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers which has the largest sum.
kadane's algorithm explained in java
Kadane algorithm in Java

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted.

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted.


Find minimum unsorted subarray index m and n such that if you sort elements from m through n, then complete array would be sorted.

Let's understand the problem statement in simple words, 
Given an array of partially sorted integers, you have to find start index 'm' from where mismatch started that is the point from which array is not in sorted order,  and you have to find index 'n' till which index array is unsorted, and if you sort elements m through n, then entire array would be sorted.  

Let's see example to understand what is the input and expected output.

find smallest window in array sorting which will make entire array sorted
Find smallest window in array sorting which will make entire array sorted

Find all pairs of elements from array whose sum equals to given number K.

Find all pairs of elements from array whose sum equals to given number K OR
Count all pairs with given sum K OR
Java Program to find pairs on integer whose sum is equal to K.


Given an array of integers, Find all pairs of number whose sum is equal to given number K. 

You can also say, Write a Java Program to find all pairs of numbers from integer array whose sum is equal to given number K.

Let's understand what is the Input and expected Output.

find all pairs with a given sum in array in Java
Find all pairs with a given sum in array in Java

Find Smallest and Second smallest element in array.

Find Smallest and Second smallest number in array.

Given a integer array, find smallest and second smallest number in array.

Lets understand the problem statement graphically and it will be more clear,
find smallest and second smallest element in an array in java
Find smallest and second smallest element in an array in Java

Find Largest and Second Largest number in array

Find Largest and Second Largest number in array

Given a integer array, find largest and second largest number in array.

Lets understand the problem statement graphically and it will be more clear,

find the largest and second largest element in an array
Find the largest and second largest element in an array

Find Largest and Second Largest number in array and Find Smallest and Second Smallest number in array

Find Largest and Second Largest number in array OR Find the smallest and second smallest element in array.

Given a integer array, find largest and second largest number in array. 

Lets understand the problem statement graphically and it will be more clear,

find largest and second largest number in array
Find largest and second largest number in array