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 Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Check whether the vowels in a string are in alphabetical order or not
Next article icon

Check whether the given String is good for any ascending Array or not

Last Updated : 09 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S of length N. Consider any ascending array A[] such that each A[i] > 0 for all (1 <= i <= N) and some conditions, the task is to output YES/NO, by checking that the above-given conditions are true for all possible ascending A[]'s or not with given S.

  • Sum up all the elements of A[] at each index i, where S[i] = 1 in a variable let's say X.
  • Sum up all the elements of A[] at each index i, where S[i] = 0 in a variable let's say Y.
  • Then |X - Y| must be less than or equal to Max(A[]).

Any array is said to be ascending, If all element except the last is less than or equal to its next element. Formally, A[] = {A1 <= A2 <= A3 <= A4 . . . . <= A5}.

Examples: All the below arrays are ascending arrays.

  • A[] = {1, 2, 3, 5}
  • A[] = {5, 6, 7, 8}
  • A[] = {2, 2, 2, 2}
  • A[] = {3, 6, 8, 8}

Examples:

Input: N = 4, S = 1010

Output: YES

Explanation: Let us check the given S for multiple ascending arrays:

  • A[] = {2, 5, 8, 9}
    • S contains 1s at index 1 and 3, Then X = A[1] + A[3] = 2+8 = 10
    • S contains 0s at index 2 and 4, Then X = A[2] + A[4] = 9+5 =14
    • |X - Y| = |10 - 14| = 4.
    • Max element of A[] = 9
    • It can be checked that (|X-Y| = 4) <= 9. Thus, A[] satisfies that given condition with given S.
  • A[] = {2, 2, 2, 2}
    • S contains 1s at index 1 and 3, Then X = A[1] + A[3] = 2+2 = 4
    • S contains 0s at index 2 and 4, Then X = A[2] + A[4] = 2+2 = 4
    • |X - Y| = |4 - 4| = 0.
    • Max element of A[] = 9
    • It can be checked that (|X-Y| = 0) <= 9. Thus, A[] satisfies that given condition with given S.

For any possible ascending array A[] of length 4. The given conditions will always be true. Therefore, output is YES.

Input: N = 5, S = 00001

Output: NO

Explanation: S doesn't follow all the given conditions with all possible ascending A[]'s. One such A[] is: {2, 2, 2, 2, 2}. For this A[], X and Y will be 2 and 8 respectively and then |X - Y| = |2 - 8| = 6 and Max(A[]) = 2. Thus, the condition (|X - Y| = 6) <= 2 fails. Therefore, output is NO.

Approach: Implement the idea below to solve the problem

This is an observation-based problem. Reverse S and start counting 1s. Then go with the approach of balanced parenthesis. If multiple 1 or 0 are found and the count of 1s goes less than -1 or greater than 1, Then it is not possible all cases else it is possible.

Steps were taken to solve the problem:

  • Create a boolean variable, let say Flag and mark it initially True.
  • Declare a variable let say Count to store the frequency of 1s.
  • Run a loop from back of the String and follow below steps under the scope of loop:
    • If (current character == 1)
      • Decrement Count
    • Else
      • Increment Count
  • If (Count < -1 || Count > 1)
    • Flag = false
    • Break the loop
  • If (Flag), then output YES.

Code to implement the approach:

C++
#include <iostream> #include <string>  // Declare the function prototype void Satisfies_all_A(int N, std::string S);  // Driver Function int main() {     // Inputs     int N = 5;     std::string S = "00001";      // Function call     Satisfies_all_A(N, S);      return 0; }  // Method to check that given S satisfies // all possible ascending arrays A[] void Satisfies_all_A(int N, std::string S) {     // Flag     bool flag = true;      // Variable to count 1s     int count = 0;      // Loop for traversing S from back     // and counting 1s     for (int i = N - 1; i >= 0; i--) {          if (S[i] == '1')             count--;         else             count++;          // If discussed condition breaches         // Then marking flag false         // and breaking the loop         if (count < -1 || count > 1) {             flag = false;             std::cout << "NO" << std::endl;             break;         }     }      // Printing YES if count of 1s are     // appropriate     if (flag)         std::cout << "YES" << std::endl; } 
Java
// Java code to implement the approach import java.util.*;  // Driver class public class GFG {     // Driver Function     public static void main(String[] args)     {         // Inputs         int N = 5;         String S = "00001";          // Function_call         Satisfies_all_A(N, S);     }      // Method to check that given S satisfies     // all possible ascending arrays A[]     public static void Satisfies_all_A(int N, String S)     {         // Flag         boolean flag = true;          // Variable to count 1s         int count = 0;          // Loop for traversing S from back         // and counting 1s         for (int i = N - 1; i >= 0; i--) {              if (S.charAt(i) == '1')                 count--;             else                 count++;              // If discussed condition breaches             // Then marking flag false             // and breaking the loop             if (count < -1 || count > 1) {                 flag = false;                 System.out.println("NO");                 break;             }         }          // Printing YES if count of 1s are         // appropriate         if (flag)             System.out.println("YES");     } } 
Python3
# Method to check that given S satisfies # all possible ascending arrays A[] def satisfies_all_A(N, S):     # Flag     flag = True      # Variable to count 1s     count = 0      # Loop for traversing S from back     # and counting 1s     for i in range(N - 1, -1, -1):         if S[i] == '1':             count -= 1         else:             count += 1          # If discussed condition breaches         # Then marking flag false         # and breaking the loop         if count < -1 or count > 1:             flag = False             print("NO")             break      # Printing YES if count of 1s are     # appropriate     if flag:         print("YES")  # Driver code if __name__ == "__main__":     # Inputs     N = 5     S = "00001"      # Function call     satisfies_all_A(N, S) 
C#
using System;  public class GFG {     // Main Method     public static void Main(string[] args)     {         // Inputs         int N = 5;         string S = "00001";          // Function call         SatisfiesAllA(N, S);     }      // Method to check that given S satisfies     // all possible ascending arrays A[]     public static void SatisfiesAllA(int N, string S)     {         // Flag         bool flag = true;          // Variable to count 1s         int count = 0;          // Loop for traversing S from back         // and counting 1s         for (int i = N - 1; i >= 0; i--) {             if (S[i] == '1')                 count--;             else                 count++;              // If discussed condition breaches             // Then marking flag false             // and breaking the loop             if (count < -1 || count > 1) {                 flag = false;                 Console.WriteLine("NO");                 break;             }         }          // Printing YES if count of 1s are         // appropriate         if (flag)             Console.WriteLine("YES");     } } 
JavaScript
// Function to check that given S satisfies // all possible ascending arrays A[] function satisfiesAllA(N, S) {     // Flag     let flag = true;      // Variable to count 1s     let count = 0;      // Loop for traversing S from back     // and counting 1s     for (let i = N - 1; i >= 0; i--) {         if (S[i] === '1') {             count -= 1;         } else {             count += 1;         }          // If discussed condition breaches         // Then marking flag false         // and breaking the loop         if (count < -1 || count > 1) {             flag = false;             console.log("NO");             break;         }     }      // Printing YES if count of 1s are     // appropriate     if (flag) {         console.log("YES");     } }  // Driver code // Inputs const N = 5; const S = "00001";  // Function call satisfiesAllA(N, S); 

Output
NO

Time Complexity: O(N)
Auxiliary space: O(1)


Next Article
Check whether the vowels in a string are in alphabetical order or not
author
pradeep6036ymca
Improve
Article Tags :
  • Strings
  • Geeks Premier League
  • DSA
  • Geeks Premier League 2023
Practice Tags :
  • Strings

Similar Reads

  • Check whether a given array is a k sorted array or not
    Given an array of n distinct elements. Check whether the given array is a k sorted array or not. A k sorted array is an array where each element is at most k distances away from its target position in the sorted array. For example, let us consider k is 2, an element at index 7 in the sorted array, c
    12 min read
  • Check whether the given array is perfect or not
    There is an array containing some non-negative integers. Check whether the array is perfect or not. An array is called perfect if it is first strictly increasing, then constant and finally strictly decreasing. Any of the three parts can be empty. Examples: Input : arr[] = {1, 8, 8, 8, 3, 2}Output :
    5 min read
  • Check whether a given string is Heterogram or not
    Given a string S. The task is to check whether a the given string is Heterogram or not. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once. Examples: Input : S = "the big dwarf only jumps" Output : Yes Each alphabet in the string S is occurred only o
    4 min read
  • Check whether the vowels in a string are in alphabetical order or not
    Given a string 'str', the task is to find whether the vowels in the string are in alphabetical order or not. The string contains only lowercase alphabets. Examples: Input: str = "aabbbddeecc" Output: Vowels are in alphabetical order The vowel characters in the string are : a, a, e, e which are in so
    9 min read
  • Sort an array of strings in ascending order with each string sorted in descending order
    Given a array of strings S[] of size N (1 ? N ? 105), sort characters of each string in descending order and then print the array of strings in ascending order. Examples: Input: s[] = {"apple", "box", "cat"} Output: pplea tca xob Explanation: Sorting each string in descending order, S[] modifies to
    9 min read
  • Check if a given array is pairwise sorted or not
    An array is considered pairwise sorted if each successive pair of numbers is in sorted (non-decreasing) order. In case of odd elements, last element is ignored and result is based on remaining even number of elements. Examples: Input : arr[] = {10, 15, 9, 9, 1, 5}; Output : Yes Pairs are (10, 15), (
    5 min read
  • Check if given Binary string follows then given condition or not
    Given binary string str, the task is to check whether the given string follows the below condition or not: String starts with a '1'.Each '1' is followed by empty string(""), '1', or "00".Each "00" is followed by empty string(""), '1'. If the given string follows the above criteria then print "Valid
    10 min read
  • Check whether Array represents a Fibonacci Series or not
    Given an array arr[] consisting of N integers, the task is to check whether a Fibonacci series can be formed using all the array elements or not. If possible, print "Yes". Otherwise, print "No". Examples: Input: arr[] = { 8, 3, 5, 13 } Output: Yes Explanation: Rearrange given array as {3, 5, 8, 13}
    9 min read
  • Check if a given string is a Reverse Bitonic String or not
    Given a string str, the task is to check if that string is a Reverse Bitonic string or not. If the string str is reverse Bitonic string, then print "YES". Otherwise, print "NO". A Reverse Bitonic String is a string in which the characters are arranged in decreasing order followed by increasing order
    6 min read
  • Check whether the given string is a valid identifier
    Given a string str, the task is to check if the string is a valid identifier or not. In order to qualify as a valid identifier, the string must satisfy the following conditions: It must start with an either underscore(_) or any of the characters from the ranges ['a', 'z'] and ['A', 'Z'].There must n
    6 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