Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if the Array elements can be made 0 with given conditions
Next article icon

Check if all array elements can be converted to K using given operations

Last Updated : 19 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer array arr of size N and an integer K, the task is to make all elements of the array equal to K using the following operations: 
 

  • Choose an arbitrary subarray [l….r] of the input array
  • Replace all values of this subarray equal to the [((r – l) + 2) / 2]th value in sorted subarray [l…r]

Examples: 
 

Input: arr [ ] = {5, 4, 3, 1, 2, 6, 7, 8, 9, 10}, K = 3 
Output: YES 
Explanation: 
Choose first five elements and replace all elements with 3: arr = {3, 3, 3, 3, 3, 6, 7, 8, 9, 10} 
Now take forth to sixth elements and replace all elements with 3: arr = {3, 3, 3, 3, 3, 3, 7, 8, 9, 10} 
By applying same operations we can make all elements of arr equal to K: arr = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}
Input: arr [ ] = {3, 1, 2, 3}, K = 4 
Output: NO 
 

 

Approach: 
 

  • We can observe that it is possible to make all elements of the array equal to K only if following two conditions are satisfied: 
    1. There must be at least one element equal to K.
    2. There must exist a continuous triplet such that any two values of that triplet is greater than or equal to K.
  • To solve this problem, we need to create an auxiliary array, say aux[] , that contains three values 0, 1, 2.
  • The final task is to check if it is possible to make all elements of aux array equal to 1. If two out of three continuous elements in aux[] are greater than 0, then we can take a subarray of size 3 and make all elements of that subarray equal to 1. And then we expand this logic through the entire array.

Below is the implementation of above approach: 
 

C++




// C++ implementation of above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function that prints
// whether is to possible
// to make all elements
// of the array equal to K
void makeAllK(int a[], int k, int n)
{
    vector<int> aux;
 
    bool one_found = false;
 
    // Fill vector aux
    // according to the
    // above approach
    for (int i = 0; i < n; i++) {
 
        if (a[i] < k)
            aux.push_back(0);
 
        else if (a[i] == k) {
            aux.push_back(1);
            one_found = true;
        }
 
        else
            aux.push_back(2);
    }
 
    // Condition if K
    // does not exist in
    // the given array
    if (one_found == false) {
        cout << "NO"
             << "\n";
        return;
    }
 
    bool ans = false;
 
    if (n == 1
        && aux[0] == 1)
        ans = true;
 
    if (n == 2
        && aux[0] > 0
        && aux[1] > 1)
        ans = true;
 
    for (int i = 0; i < n - 2; i++) {
 
        // Condition for minimum
        // two elements is
        // greater than 0 in
        // pair of three elements
        if (aux[i] > 0
            && aux[i + 1] > 0) {
 
            ans = true;
            break;
        }
 
        else if (aux[i] > 0
                 && aux[i + 2] > 0) {
            ans = true;
            break;
        }
 
        else if (aux[i + 2] > 0
                 && aux[i + 1] > 0) {
            ans = true;
            break;
        }
    }
 
    if (ans == true)
        cout << "YES"
             << "\n";
    else
        cout << "NO"
             << "\n";
}
 
// Driver Code
int main()
{
    int arr[]
        = { 1, 2, 3,
            4, 5, 6,
            7, 8, 9, 10 };
 
    int K = 3;
 
    int size = sizeof(arr)
               / sizeof(arr[0]);
 
    makeAllK(arr, K, size);
 
    return 0;
}
 
 

Java




// Java implementation of the above approach
import java.util.*;
 
class GFG{
 
// Function that prints
// whether is to possible
// to make all elements
// of the array equal to K
static void makeAllK(int a[], int k, int n)
{
    Vector<Integer> aux = new Vector<Integer>();
 
    boolean one_found = false;
 
    // Fill vector aux according
    // to the above approach
    for(int i = 0; i < n; i++)
    {
       if (a[i] < k)
           aux.add(0);
        
       else if (a[i] == k)
       {
           aux.add(1);
           one_found = true;
       }
       else
           aux.add(2);
    }
 
    // Condition if K does not 
    // exist in the given array
    if (one_found == false)
    {
        System.out.print("NO" + "\n");
        return;
    }
 
    boolean ans = false;
 
    if (n == 1 && aux.get(0) == 1)
        ans = true;
 
    if (n == 2 && aux.get(0) > 0 &&
                  aux.get(1) > 1)
        ans = true;
 
    for(int i = 0; i < n - 2; i++)
    {
        
       // Condition for minimum
       // two elements is
       // greater than 0 in
       // pair of three elements
       if (aux.get(i) > 0 &&
           aux.get(i + 1) > 0)
       {
           ans = true;
           break;
       }
       else if (aux.get(i) > 0 &&
                aux.get(i + 2) > 0)
       {
           ans = true;
           break;
       }
       else if (aux.get(i + 2) > 0 &&
                aux.get(i + 1) > 0)
       {
           ans = true;
           break;
       }
    }
 
    if (ans == true)
        System.out.print("YES" + "\n");
    else
        System.out.print("NO" + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3, 4, 5,
                  6, 7, 8, 9, 10 };
    int K = 3;
    int size = arr.length;
 
    makeAllK(arr, K, size);
 
}
}
 
// This code is contributed by amal kumar choubey
 
 

Python3




# Python3 implementation of above approach
 
# Function that prints whether is
# to possible to make all elements
# of the array equal to K
def makeAllK(a, k, n):
     
    aux = []
    one_found = False
 
    # Fill vector aux according
    # to the above approach
    for i in range(n):
        if (a[i] < k):
            aux.append(0)
 
        elif (a[i] == k):
            aux.append(1)
            one_found = True
 
        else:
            aux.append(2)
 
    # Condition if K does
    # not exist in the given
    # array
    if (one_found == False):
        print("NO")
        return
 
    ans = False
 
    if (n == 1 and aux[0] == 1):
        ans = True
 
    if (n == 2 and aux[0] > 0 and aux[1] > 1):
        ans = True
 
    for i in range(n - 2):
         
        # Condition for minimum two
        # elements is greater than
        # 0 in pair of three elements
        if (aux[i] > 0 and aux[i + 1] > 0):
            ans = True
            break
 
        elif (aux[i] > 0 and aux[i + 2] > 0):
            ans = True
            break
 
        elif (aux[i + 2] > 0 and aux[i + 1] > 0):
            ans = True
            break
 
    if (ans == True):
        print("YES")
    else:
        print("NO")
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
    K = 3
    size = len(arr)
 
    makeAllK(arr, K, size)
 
# This code is contributed by Surendra_Gangwar
 
 

C#




// C# implementation of the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function that prints
// whether is to possible
// to make all elements
// of the array equal to K
static void makeAllK(int []a, int k, int n)
{
    List<int> aux = new List<int>();
 
    bool one_found = false;
 
    // Fill vector aux according
    // to the above approach
    for(int i = 0; i < n; i++)
    {
       if (a[i] < k)
       {
           aux.Add(0);
       }
       else if (a[i] == k)
       {
           aux.Add(1);
           one_found = true;
       }
       else
           aux.Add(2);
    }
 
    // Condition if K does not
    // exist in the given array
    if (one_found == false)
    {
        Console.Write("NO" + "\n");
        return;
    }
 
    bool ans = false;
    if (n == 1 && aux[0] == 1)
        ans = true;
 
    if (n == 2 && aux[0] > 0 &&
                  aux[1] > 1)
        ans = true;
 
    for(int i = 0; i < n - 2; i++)
    {
        
       // Condition for minimum
       // two elements is
       // greater than 0 in
       // pair of three elements
       if (aux[i] > 0 &&
           aux[i + 1] > 0)
       {
           ans = true;
           break;
       }
       else if (aux[i] > 0 &&
                aux[i + 2] > 0)
       {
           ans = true;
           break;
       }
       else if (aux[i + 2] > 0 &&
                aux[i + 1] > 0)
       {
           ans = true;
           break;
       }
    }
    if (ans == true)
        Console.Write("YES" + "\n");
    else
        Console.Write("NO" + "\n");
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 3, 4, 5,
                  6, 7, 8, 9, 10 };
    int K = 3;
    int size = arr.Length;
 
    makeAllK(arr, K, size);
}
}
 
// This code is contributed by amal kumar choubey
 
 

Javascript




<script>
 
// Javascript implementation of above approach
 
// Function that prints
// whether is to possible
// to make all elements
// of the array equal to K
function makeAllK(a, k, n)
{
    var aux = [];
 
    var one_found = false;
 
    // Fill vector aux
    // according to the
    // above approach
    for (var i = 0; i < n; i++) {
 
        if (a[i] < k)
            aux.push(0);
 
        else if (a[i] == k) {
            aux.push(1);
            one_found = true;
        }
 
        else
            aux.push(2);
    }
 
    // Condition if K
    // does not exist in
    // the given array
    if (one_found == false) {
        document.write( "NO" + "<br>");
        return;
    }
 
    var ans = false;
 
    if (n == 1
        && aux[0] == 1)
        ans = true;
 
    if (n == 2
        && aux[0] > 0
        && aux[1] > 1)
        ans = true;
 
    for (var i = 0; i < n - 2; i++) {
 
        // Condition for minimum
        // two elements is
        // greater than 0 in
        // pair of three elements
        if (aux[i] > 0
            && aux[i + 1] > 0) {
 
            ans = true;
            break;
        }
 
        else if (aux[i] > 0
                 && aux[i + 2] > 0) {
            ans = true;
            break;
        }
 
        else if (aux[i + 2] > 0
                 && aux[i + 1] > 0) {
            ans = true;
            break;
        }
    }
 
    if (ans == true)
        document.write( "YES"+ "<br>")
    else
        document.write( "NO"+ "<br>")
}
 
// Driver Code
var arr
    = [1, 2, 3,
        4, 5, 6,
        7, 8, 9, 10];
var K = 3;
var size = arr.length;
makeAllK(arr, K, size);
 
// This code is contributed by rutvik_56.
</script>
 
 
Output: 
YES

 

Time Complexity: O(N) 
Auxiliary Space: O(N)
 



Next Article
Check if the Array elements can be made 0 with given conditions

N

nitinkr8991
Improve
Article Tags :
  • Arrays
  • DSA
  • subarray
Practice Tags :
  • Arrays

Similar Reads

  • Check if Array Elemnts can be Made Equal with Given Operations
    Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X. Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.Note : Only one operation can be performed on a numbe
    6 min read
  • Check if the Array elements can be made 0 with given conditions
    Given two arrays arr[] and arr2[], and a value K, the task is to check whether the array arr[] can be made to all zeros such that in each operation all elements less than K are made to 0 else they are subtracted by K then the K gets decayed by the smallest value of the array arr2[] whose arr[i] is n
    10 min read
  • Check if even and odd count of elements can be made equal in Array
    Given an array Arr[] of N integers and an integer K, the task is to find if it is possible to make the count of even and odd elements equal by performing the following operations at most K times: Choose any index i such that Arr[i] is even and divide it by 2.Choose any index i such that Arr[i] is od
    9 min read
  • Check if all array elements can be reduced to less than X
    Given an array A[] consisting of N positive integers and an integer X, the task is to determine if it is possible to convert all array elements to less than X by performing the following operations: Select 2 distinct indices j and k.Select an index i, where A[i] > X.Replace A[i] = gcd(A[j], A[k])
    15+ min read
  • Check if N can be converted to the form K power K by the given operation
    Given a positive number N, we have to find whether N can be converted to the form KK where K is also a positive integer, using the following operation any number of times : Choose any digit less than the current value of N, say d.N = N - d2, change N each time If it is possible to express the number
    15+ min read
  • Check if array elements can become same using one external number
    Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X: Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.The task is to check whether there exists a number X,
    11 min read
  • Check if sum of the given array can be reduced to 0 by reducing array elements by K
    Given an array arr[] consisting of N integers and an integer K, the task is to check if the sum of the array can be reduced to 0 by subtracting array elements by K any number of times. Examples: Input: arr[ ]= {-3, 2, -1, 5, 1}, K=2Output: "Yes"Explanation: Sum of the array is 4. Therefore, decreasi
    5 min read
  • Make all Array elements equal to zero in atmost m operations
    Given an integer array A[] of size N and integer k. For a fixed value p, choose an index i (1 ≤ i ≤ n) and assign A[i] = max(0, A[i] − p), this counts as one operation, and the task is to find the smallest value of p such that all the elements of the array A[] become 0 in at most k operations. Examp
    10 min read
  • Check if Array sum can be made equal to X using K triplet increment operations
    Given an array arr of length N and two integers K and X. For every element arri in the array, if arri > 0 then the elements which are adjacent to it and the element itself will get incremented by 2 for all 1≤i≤N. Check if the sum of all array elements after performing the K operation is equal to
    8 min read
  • Check if a sorted array can be divided in pairs whose sum is k
    Given a sorted array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair k.Expected time complexity O(n) and extra space O(1). This problem is a variation of below problem, but has a different interesting solution that r
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences