The Wayback Machine - https://web.archive.org/web/20241108100358/https://www.geeksforgeeks.org/count-distinct-elements-in-every-window-of-size-k/
Open In App

Count distinct elements in every window of size k

Last Updated : 01 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of size N and an integer K, return the count of distinct numbers in all windows of size K. 

Examples: 

Input: arr[] = {1, 2, 1, 3, 4, 2, 3}, K = 4
Output: 3 4 4 3
Explanation: First window is {1, 2, 1, 3}, count of distinct numbers is 3
                      Second window is {2, 1, 3, 4} count of distinct numbers is 4
                      Third window is {1, 3, 4, 2} count of distinct numbers is 4
                      Fourth window is {3, 4, 2, 3} count of distinct numbers is 3

Input: arr[] = {1, 2, 4, 4}, K = 2
Output: 2 2 1
Explanation: First window is {1, 2}, count of distinct numbers is 2
                      First window is {2, 4}, count of distinct numbers is 2
                      First window is {4, 4}, count of distinct numbers is 1

This problem has appeared in Microsoft Interview Question.

Approaches to Count distinct elements in every window of size K:

[Naive Approach] Traversing all windows of size K – O(N * K * K) Time and O(1) Space:

Traverse the given array considering every window of size K in it and keeping a count on the distinct elements of the window.

Below is the implementation of the above approach:

C++
// C++ program to count distinct
// elements in every window of size K

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

// Counts distinct elements in window of size K
int countWindowDistinct(int win[], int K)
{
    int dist_count = 0;

    // Traverse the window
    for (int i = 0; i < K; i++) {
        // Check if element arr[i] exists in arr[0..i-1]
        int j;
        for (j = 0; j < i; j++)
            if (win[i] == win[j])
                break;
        if (j == i)
            dist_count++;
    }
    return dist_count;
}

// Counts distinct elements in all windows of size k
void countDistinct(int arr[], int N, int K)
{
    // Traverse through every window
    for (int i = 0; i <= N - K; i++)
        cout << countWindowDistinct(arr + i, K) << endl;
}

// Driver's code
int main()
{
    int arr[] = {1, 2, 1, 3, 4, 2, 3}, K = 4;
    int N = sizeof(arr) / sizeof(arr[0]);

    // Function call
    countDistinct(arr, N, K);
    return 0;
}
Java
// Java program to count distinct elements in every
// window of size K

import java.util.Arrays;

class Test {

    // Counts distinct elements in window of size K
    static int countWindowDistinct(int win[], int K)
    {
        int dist_count = 0;

        // Traverse the window
        for (int i = 0; i < K; i++) {
            // Check if element arr[i] exists in arr[0..i-1]
            int j;
            for (j = 0; j < i; j++)
                if (win[i] == win[j])
                    break;
            if (j == i)
                dist_count++;
        }
        return dist_count;
    }

    // Counts distinct elements in all windows of size K
    static void countDistinct(int arr[], int N, int K)
    {
        // Traverse through every window
        for (int i = 0; i <= N - K; i++)
            System.out.println(countWindowDistinct(
                Arrays.copyOfRange(arr, i, arr.length), K));
    }

    // Driver's code
    public static void main(String args[])
    {
        int arr[] = {1, 2, 1, 3, 4, 2, 3}, K = 4;
        
          // Function call
        countDistinct(arr, arr.length, K);
    }
}
Python
# Python3 program to count distinct
# elements in every window of size K

import math as mt

# Counts distinct elements in window
# of size K


def countWindowDistinct(win, K):

    dist_count = 0

    # Traverse the window
    for i in range(K):

        # Check if element arr[i] exists
        # in arr[0..i-1]
        j = 0
        while j < i:
            if (win[i] == win[j]):
                break
            else:
                j += 1
        if (j == i):
            dist_count += 1

    return dist_count


# Counts distinct elements in all
# windows of size k
def countDistinct(arr, N, K):

    # Traverse through every window
    for i in range(N - K + 1):
        print(countWindowDistinct(arr[i:K + i], K))


# Driver's Code
if __name__=='__main__':
  arr = [1, 2, 1, 3, 4, 2, 3]
  K = 4
  N = len(arr)
  
  # Function call
  countDistinct(arr, N, K)

# This code is contributed by
# Mohit kumar 29
C#
// Simple C# program to count distinct
// elements in every window of size K
using System;
using System.Collections.Generic;

class GFG {
    // Counts distinct elements in
    // window of size K
    static int countWindowDistinct(int[] win, int K)
    {
        int dist_count = 0;

        // Traverse the window
        for (int i = 0; i < K; i++) {
            // Check if element arr[i]
            // exists in arr[0..i-1]
            int j;
            for (j = 0; j < i; j++)
                if (win[i] == win[j])
                    break;
            if (j == i)
                dist_count++;
        }
        return dist_count;
    }

    // Counts distinct elements in
    // all windows of size k
    static void countDistinct(int[] arr, int N, int K)
    {
        // Traverse through every window
        for (int i = 0; i <= N - K; i++) {
            int[] newArr = new int[K];
            Array.Copy(arr, i, newArr, 0, K);
            Console.WriteLine(
                countWindowDistinct(newArr, K));
        }
    }

    // Driver's Code
    public static void Main(String[] args)
    {
        int[] arr = {1, 2, 1, 3, 4, 2, 3};
        int K = 4;
        
          // Function call
        countDistinct(arr, arr.Length, K);
    }
}

// This code is contributed by Princi Singh
JavaScript
// Javascript program to count distinct elements in every
// window of size k

// Counts distinct elements in window of size k
    function countWindowDistinct(win, k)
    {
        let dist_count = 0;
 
        // Traverse the window
        for (let i = 0; i < k; i++) {
            // Check if element arr[i] exists in arr[0..i-1]
            let j;
            for (j = 0; j < i; j++)
                if (win[i] == win[j])
                    break;
            if (j == i)
                dist_count++;
        }
        return dist_count;
    }
 
    // Counts distinct elements in all windows of size k
    function countDistinct(arr, N, K)
    {
        // Traverse through every window
        for (let i = 0; i <= N - K; i++)
            document.write(countWindowDistinct(arr.slice(i, arr.length), K) + "<br/>");
    }


// Driver program 

      let arr = [1, 2, 1, 3, 4, 2, 3], K = 4;
 
        countDistinct(arr, arr.length, K);
 
 // This code is contributed by target_2.

Output
3
4
4
3

Time complexity: O(N * K2)
Auxiliary Space: O(1) 

[Expected Approach] Sliding Window Technique – O(N) Time and O(N) Space:

The trick is to use the count of the previous window while sliding the window. To do this a hash map can be used that stores elements of the current window. The hash-map is used for addition and removal of an element while keeping track of distinct elements. The problem deals with finding the count of distinct elements in a window of length k, at any step while shifting the window and discarding all the computation done in the previous step, even though k – 1 elements are same from the previous adjacent window. For example, assume that elements from index i to i + k – 1 are stored in a Hash Map as an element-frequency pair. So, while updating the Hash Map in range i + 1 to i + k, reduce the frequency of the i-th element by 1 and increase the frequency of (i + k)-th element by 1. 
Insertion and deletion from the HashMap takes constant time.

Below is the implementation of the above approach:

C++
// C++ program for the above approach

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

void countDistinct(int arr[], int K, int N)
{
    // Creates an empty hashmap hm
    unordered_map<int, int> hm;

    // initialize distinct element count for current window
    int dist_count = 0;

    // Traverse the first window and store count
    // of every element in hash map
    for (int i = 0; i < K; i++) {
        if (hm[arr[i]] == 0) {
            dist_count++;
        }
      
        hm[arr[i]] += 1;
    }

    // Print count of first window
    cout << dist_count << endl;

    // Traverse through the remaining array
    for (int i = K; i < N; i++) {
        // Remove first element of previous window
        // If there was only one occurrence, then reduce distinct count.
        if (hm[arr[i - K]] == 1) {
            dist_count--;
        }
        // reduce count of the removed element
        hm[arr[i - K]] -= 1;

        // Add new element of current window
        // If this element appears first time,
        // increment distinct element count

        if (hm[arr[i]] == 0) {
            dist_count++;
        }
        hm[arr[i]] += 1;

        // Print count of current window
        cout << dist_count << endl;
    }
}

// Driver's code
int main()
{
    int arr[] = {1, 2, 1, 3, 4, 2, 3};
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 4;
  
      // Function call
    countDistinct(arr, K, N);

    return 0;
}
Java
// Java program for the above approach

import java.util.HashMap;

class CountDistinctWindow {
    static void countDistinct(int arr[], int K)
    {
        // Creates an empty hashMap hM
        HashMap<Integer, Integer> hM
            = new HashMap<Integer, Integer>();

        // Traverse the first window and store count
        // of every element in hash map
        for (int i = 0; i < K; i++)
            hM.put(arr[i], hM.getOrDefault(arr[i], 0) + 1);

        // Print count of first window
        System.out.println(hM.size());

        // Traverse through the remaining array
        for (int i = K; i < arr.length; i++) {

            // Remove first element of previous window
            // If there was only one occurrence
            if (hM.get(arr[i - K]) == 1) {
                hM.remove(arr[i - K]);
            }

            else // reduce count of the removed element
                hM.put(arr[i - K], hM.get(arr[i - K]) - 1);

            // Add new element of current window
            // If this element appears first time,
            // set its count as 1,
            hM.put(arr[i], hM.getOrDefault(arr[i], 0) + 1);

            // Print count of current window
            System.out.println(hM.size());
        }
    }

    // Driver's code
    public static void main(String arg[])
    {
        int arr[] = { 1, 2, 1, 3, 4, 2, 3 };
        int K = 4;

        // Function call
        countDistinct(arr, K);
    }
}
Python
# An efficient Python program to
# count distinct elements in
# every window of size K
from collections import defaultdict


def countDistinct(arr, K, N):

    # Creates an empty hashmap hm
    mp = defaultdict(lambda: 0)

    # initialize distinct element
    # count for current window
    dist_count = 0

    # Traverse the first window and store count
    # of every element in hash map
    for i in range(K):
        if mp[arr[i]] == 0:
            dist_count += 1
        mp[arr[i]] += 1

    # Print count of first window
    print(dist_count)

    # Traverse through the remaining array
    for i in range(K, N):

        # Remove first element of previous window
        # If there was only one occurrence,
        # then reduce distinct count.
        if mp[arr[i - K]] == 1:
            dist_count -= 1
        mp[arr[i - K]] -= 1

    # Add new element of current window
    # If this element appears first time,
    # increment distinct element count
        if mp[arr[i]] == 0:
            dist_count += 1
        mp[arr[i]] += 1

        # Print count of current window
        print(dist_count)

# Driver's code
if __name__=='__main__':
  arr = [1, 2, 1, 3, 4, 2, 3]
  N = len(arr)
  K = 4

  # Function call
  countDistinct(arr, K, N)
C#
// C# program for the above approach

using System;
using System.Collections.Generic;

public class CountDistinctWindow {
    static void countDistinct(int[] arr, int K)
    {
        // Creates an empty hashMap hM
        Dictionary<int, int> hM
            = new Dictionary<int, int>();

        // initialize distinct element count for
        // current window
        int dist_count = 0;

        // Traverse the first window and store count
        // of every element in hash map
        for (int i = 0; i < K; i++) {
            if (!hM.ContainsKey(arr[i])) {
                hM.Add(arr[i], 1);
                dist_count++;
            }
            else {
                int count = hM[arr[i]];
                hM.Remove(arr[i]);
                hM.Add(arr[i], count + 1);
            }
        }

        // Print count of first window
        Console.WriteLine(dist_count);

        // Traverse through the remaining array
        for (int i = K; i < arr.Length; i++) {

            // Remove first element of previous window
            // If there was only one occurrence, then
            // reduce distinct count.
            if (hM[arr[i - K]] == 1) {
                hM.Remove(arr[i - K]);
                dist_count--;
            }
            else // reduce count of the removed element
            {
                int count = hM[arr[i - K]];
                hM.Remove(arr[i - K]);
                hM.Add(arr[i - K], count - 1);
            }

            // Add new element of current window
            // If this element appears first time,
            // increment distinct element count
            if (!hM.ContainsKey(arr[i])) {
                hM.Add(arr[i], 1);
                dist_count++;
            }
            else // Increment distinct element count
            {
                int count = hM[arr[i]];
                hM.Remove(arr[i]);
                hM.Add(arr[i], count + 1);
            }

            // Print count of current window
            Console.WriteLine(dist_count);
        }
    }

    // Driver's code
    public static void Main(String[] arg)
    {
        int[] arr = {1, 2, 1, 3, 4, 2, 3};
        int K = 4;
      
          // Function call
        countDistinct(arr, K);
    }
}
JavaScript
// Javascript program to count distinct elements in
// every window of size k
    
   function countDistinct(arr, k)
    {
        // Creates an empty hashMap hM
        let hM = new Map();

        // Traverse the first window and store count
        // of every element in hash map
        for (let i = 0; i < k; i++)
        {
            if(hM.has(arr[i]))
            hM.set(arr[i], hM.get(arr[i])+1)
            else
            hM.set(arr[i], 1);
        }

        // Print count of first window
        console.log(hM.size);

        // Traverse through the remaining array
        for (let i = k; i < arr.length; i++) {

            // Remove first element of previous window
            // If there was only one occurrence
            if (hM.get(arr[i - k]) == 1) {
                hM.delete(arr[i - k]);
            }

            else // reduce count of the removed element
                hM.set(arr[i - k],  hM.get(arr[i - k]) - 1);            

            // Add new element of current window
            // If this element appears first time,
            // set its count as 1,
            if(hM.has(arr[i]))
            hM.set(arr[i], hM.get(arr[i])+1)
            else
            hM.set(arr[i], 1);

            // Print count of current window
               console.log(hM.size);
        }
    }


// Driver code
    let arr = [1, 2, 1, 3, 4, 2, 3];
    let size = arr.length;
    let k = 4;
    countDistinct(arr, k, size);
    

Output
3
4
4
3

Time complexity: O(N), A single traversal of the array is required.
Auxiliary Space: O(N), Since the hashmap requires linear space.

Working:

Below is the illustration of finding count of distinct elements in every window of size 4:




Previous Article
Next Article

Similar Reads

Minimum window size containing atleast P primes in every window of given range
Given three integers X, Y and P, the task is to find the minimum window size K such that every window in the range [X, Y] of this size have atleast P prime numbers.Examples: Input: X = 2, Y = 8, P = 2 Output: 4 Explanation: In the range [2, 8], window size of 4 contains atleast 2 primes in each window. Possible Windows - {2, 3, 4, 5} - No of Primes
15+ min read
First negative integer in every window of size k
Given an array and a positive integer k, find the first negative integer for each window(contiguous subarray) of size k. If a window does not contain a negative integer, then print 0 for that window. Examples: Input : arr[] = {-8, 2, 3, -6, 10}, k = 2 Output : -8 0 -6 -6 First negative integer for each window of size k {-8, 2} = -8 {2, 3} = 0 (does
15+ min read
Maximum of minimums of every window size in a given array
Given an integer array arr[] of size n, find the maximum of the minimums for every window size in the given array. The window size varies from 1 to n. Example: Input : arr[] = {10, 20, 30}Output: {30, 20, 10}Explanation: First element in output indicates maximum of minimums of all windows of size 1. Minimums of windows of size 1 are {10} , {20} , {
14 min read
Maximum possible sum of a window in an array such that elements of same window in other array are unique
Given two arrays A and B of equal number of elements. The task is to find the maximum sum possible of a window in array B such that elements of same window in A[] are unique. Examples: Input: A = [0, 1, 2, 3, 0, 1, 4] B = [9, 8, 1, 2, 3, 4, 5] Output: sum = 20 The maximum sum possible in B[] such that all corresponding elements in A[] are unique is
10 min read
Count all distinct pairs of repeating elements from the array for every array element
Given an array arr[] of N integers. For each element in the array, the task is to count the possible pairs (i, j), excluding the current element, such that i < j and arr[i] = arr[j]. Examples: Input: arr[] = {1, 1, 2, 1, 2}Output: 2 2 3 2 3Explanation:For index 1, remaining elements after excluding current element are [1, 2, 1, 2]. So the count
7 min read
Count of distinct differences between two maximum elements of every Subarray
Given an array arr[] of size N. The task is to count the number of unique differences between the two maximum elements of every subarray of size at least 2 of the given array. Examples: Input: arr[] = { 5, 1, 3 }, N = 3Output: 2Explanation: The subarrays are {5, 1}, {5, 1, 3}, {1, 3}.{5, 1} - First max = 5; Second max = 1; difference = (5 - 1) = 4{
11 min read
Maximize count of distinct elements in a subsequence of size K in given array
Given an array arr[] of N integers and an integer K, the task is to find the maximum count of distinct elements over all the subsequences of K integers. Example: Input: arr[]={1, 1, 2, 2}, K=3Output: 2Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are 2 which is the maximum possible. Other possible s
4 min read
Count of distinct N-size Arrays with elements upto K such that adjacent element pair is either ascending or non-multiples
Given two integers N and K, find the distinct number of ways to create an array of N elements where each element is in the range [1, K] and every pair of adjacent elements (P, Q) is such that either P <= Q or P % Q > 0. Example: Input: N = 2, K = 3Output: 7Explanation: The arrays that satisfies the given conditions are {1, 1}, {1, 2}, {1, 3},
11 min read
Generate a string of size N whose each substring of size M has exactly K distinct characters
Given 3 positive integers N, M, and K. the task is to construct a string of length N consisting of lowercase letters such that each substring of length M having exactly K distinct letters.Examples: Input: N = 5, M = 2, K = 2 Output: abade Explanation: Each substring of size 2 "ab", "ba", "ad", "de" have 2 distinct letters.Input: N = 7, M = 5, K = 3
6 min read
Count all N-length arrays made up of distinct consecutive elements whose first and last elements are equal
Given two integers M and N, the task is to find the number of N-length arrays possible having non-equal adjacent elements lying in the range [1, M] having elements at first and last indices equal. Examples: Input: N = 3, M = 3Output: 6Explanation:The possible arrays are {1, 2, 1}, {1, 3, 1}, {2, 1, 2}, {2, 3, 2}, {3, 1, 3}, {3, 2, 3}. Input: N = 5,
7 min read
Count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times
Given an array arr[] consisting of N integers, the task is to find the number of different sequences that can be formed after performing the below operation on the given array arr[] any number of times. Choose two indices i and j such that arr[i] is equal to arr[j] and update all the elements in the range [i, j] in the array to arr[i]. Examples: In
7 min read
Count of N-size Arrays that can be formed starting with K such that every element is divisible by next
Given two integers N and K, the task is to find the number of different arrays of size N that can be formed having the first element as K such that every element except last, is divisible by the next element in the array. Since the count can be very large, so print the modulo 109 + 7. Examples: Input: N = 3, K = 5Output: 3Explanation:There are 3 po
11 min read
Construct a distinct elements array with given size, sum and element upper bound
Given N, size of the original array, SUM total sum of all elements present in the array and K such that no element in array is greater than K, construct the original array where all elements in the array are unique. If there is no solution, print "Not Possible". Note: All elements should be positive. Examples: Input: N = 3, SUM = 15, K = 8 Output:
10 min read
Check if Array can be divided into K groups of size C and all elements of group are distinct
Given an array A[] of size N, and two integers K and C, the task is to check if all the elements of the array can be grouped into K groups such that each group has at most C elements and all the elements of a group are distinct. Examples: Input: N=6, A=[1, 2, 1, 2, 3, 4], K = 2, C=3Output: PossibleExplanation: Let 2 groups be k1, k2 of capacity 3.I
10 min read
Program to find the final size of Congestion Window in TCP Reno
Given the initial congestion window size cwnd, threshold value ssthresh, connection time rtt and an array arr where arr[i] implies the time when a packet loss is detected. The task is to find the final congestion window size when all the packet drops are being encountered by the sender. The TCP Reno follows below conditions: The initial value of cw
7 min read
Find the final size of Congestion Window in TCP Tahoe
Given the initial congestion window size cwnd, threshold value ssthresh, connection time rtt and an array arr where arr[i] implies the time when a packet loss is detected. The task is to find the final congestion window size when all the packet drops are being encountered by the sender. The TCP Tahoe follows below conditions: The initial value of c
8 min read
Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time
Given an array arr[] of N integers and another integer k ? N. The task is to find the maximum element of every sub-array of size k. Examples: Input: arr[] = {9, 7, 2, 4, 6, 8, 2, 1, 5} k = 3 Output: 9 7 6 8 8 8 5 Explanation: Window 1: {9, 7, 2}, max = 9 Window 2: {7, 2, 4}, max = 7 Window 3: {2, 4, 6}, max = 6 Window 4: {4, 6, 8}, max = 8 Window 5
8 min read
Sliding Window Maximum (Maximum of all subarrays of size K)
Given an array and an integer K, find the maximum for each and every contiguous subarray of size K. Examples : Input: arr[] = {1, 2, 3, 1, 4, 5}, K = 3 Output: 3 3 4 5Explanation: Maximum of 1, 2, 3 is 3 Maximum of 2, 3, 1 is 3 Maximum of 3, 1, 4 is 4 Maximum of 1, 4, 5 is 5 Input: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4 Output: 10 10 10
15+ min read
Count cubes of size K inscribed in a cube of size N
Given two integers N and K, the task is to find the number of cubes of size K that can be contained in a cube of size N. Examples: Input: N = 2, K = 1Output: 8Explanation:There are 8 cubes of size 1 that can be drawn inside the bigger cube of size 2. Input: N = 5, K = 2Output: 64Explanation:There are 64 cubes of size 2 can be drawn inside the bigge
4 min read
Count squares of size K inscribed in a square of size N
Given two integers N and K, the task is to find the number of squares of size K that is inscribed in a square of size N. Examples: Input: N = 4, K = 2Output: 9Explanation:There are 9 squares of size 2 inscribed in a square of size 4. Input: N = 5, K = 3Output: 9Explanation:There are 9 squares of size 3 inscribed in a square of size 5. Approach: The
4 min read
Count the number of ways to tile the floor of size n x m using 1 x m size tiles
Given a floor of size n x m and tiles of size 1 x m. The problem is to count the number of ways to tile the given floor using 1 x m tiles. A tile can either be placed horizontally or vertically. Both n and m are positive integers and 2 < = m. Examples: Input : n = 2, m = 3Output: 1Explanation: Only one combination to place two tiles of size 1 x
6 min read
Find distinct characters in distinct substrings of a string
Given a string str, the task is to find the count of distinct characters in all the distinct sub-strings of the given string.Examples: Input: str = "ABCA" Output: 18 Distinct sub-stringsDistinct charactersA1AB2ABC3ABCA3B1BC2BCA3C1CA2 Hence, 1 + 2 + 3 + 3 + 1 + 2 + 3 + 1 + 2 = 18Input: str = "AAAB" Output: 10 Approach: Take all possible sub-strings
5 min read
Check if an Array is made up of Subarrays of continuous repetitions of every distinct element
Given an array arr[], consisting of N integers, the task is to check whether the entire array is only made up of subarrays such that each subarray consists of consecutive repetitions of a single element and every distinct element in the array is part of such subarray. Examples: Input: N = 10, arr[] = {1, 1, 1, 1, 2, 2, 3, 3, 3, 3} Output: Yes Expla
11 min read
Split array into maximum subarrays such that every distinct element lies in a single subarray
Given an array, arr[] of size N, the task is to split the array into the maximum number of subarrays such that the first and the last occurrence of all distinct array element lies in a single subarray. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Split the array into subarrays {1, 1} and {2, 2}.Therefore, the required output is 2. Inpu
6 min read
Minimum row or column swaps required to make every pair of adjacent cell of a Binary Matrix distinct
Given a binary matrix M[][] of dimensions N x N, the task is to make every pair of adjacent cells in the same row or column of the given matrix distinct by swapping the minimum number of rows or columns. Examples Input: M[][] = {{0, 1, 1, 0}, {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 1}}, N = 4Output: 2Explanation: Step 1: Swapping the 2nd and 3rd rows
13 min read
Check if it is possible to create a matrix such that every row has A 1s and every column has B 1s
Given four integers N, M, A, B where N is the number of rows and M is the number of columns, the task is to check if is possible to create a binary matrix of dimensions N x M such that every row has A number of 1s and every column has a B number of 1s. If any such matrix is possible then print it else print "-1". Examples: Input: N = 3, M = 6, A =
14 min read
Minimize replacements to make every element in an array exceed every element in another given array
Given two arrays A[] and B[] of size N and M respectively, where each element is in the range [0, 9], the task is to make each element of the array A[] strictly greater than or smaller than every element in the array B[] by changing any element from either array to any number in the range [0, 9], minimum number of times. Examples: Input: A[] = [0,
10 min read
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print "Impossible". Examples: Input:
12 min read
Construct array B as last element left of every suffix array obtained by performing given operations on every suffix of given array
Given an array arr[] of N integers, the task is to print the last element left of every suffix array obtained by performing the following operation on every suffix of the array, arr[]: Copy the elements of the suffix array into an array suff[].Update ith suffix element as suff[i] = (suff[i] OR suff[i+1]) - (suff[i] XOR suff[i+1]) reducing the size
9 min read
Count pairs from an array with even product of count of distinct prime factors
Given two arrays A[] and B[] consisting of N and M integers respectively, the task is to count pairs (A[i], B[j]) such that the product of their count of distinct prime factors is even. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 5, 6}, N = 3, M = 3Output: 2Explanation: Replacing all array elements with the count of their distinct prime factors mod
11 min read
three90RightbarBannerImg