The Wayback Machine - https://web.archive.org/web/20240924232831/https://www.geeksforgeeks.org/find-equal-point-string-brackets/
Open In App

Find an equal point in a string of brackets

Last Updated : 19 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
40.8%
19.6K

Given a string of brackets, the task is to find an index k which decides the number of opening brackets is equal to the number of closing brackets. 
The string must be consists of only opening and closing brackets i.e. ‘(‘ and ‘)’.

An equal point is an index such that the number of opening brackets before it is equal to the number of closing brackets from and after.

Examples:  

Input: str = “(())))(“
Output:   4
Explanation: After index 4, string splits into (()) and ))(. The number of opening brackets in the first part is equal to the number of closing brackets in the second part.

Input: str = “))”
Output: 2
Explanation: As after 2nd position i.e. )) and “empty” string will be split into these two parts. So, in this number of opening brackets i.e. 0 in the first part is equal to the number of closing brackets in the second part i.e. also 0.

Untitled

Asked in: Amazon 

Approach 1:

  • Store the number of opening brackets that appear in the string up to every index, it must start from starting index.
  • Similarly, Store the number of closing brackets that appear in the string up to each and every index but it should be done from the last index.
  • Check if any index has the same value as opening and closing brackets.

Below is the implementation of the above approach:

C++




// C++ program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
#include<bits/stdc++.h>
using namespace std;
  
// Function to find an equal index
int findIndex(string str)
{
    int len = str.length();
    int open[len+1], close[len+1];
    int index = -1;
    memset(open, 0, sizeof (open));
    memset(close, 0, sizeof (close));
  
    open[0] = 0;
    close[len] = 0;
    if (str[0]=='(')
        open[1] = 1;
    if (str[len-1] == ')')
        close[len-1] = 1;
  
    // Store the number of opening brackets
    // at each index
    for (int i = 1; i < len; i++)
    {
        if ( str[i] == '(' )
            open[i+1] = open[i] + 1;
        else
            open[i+1] = open[i];
    }
  
    // Store the number of closing brackets
    // at each index
    for (int i = len-2; i >= 0; i--)
    {
        if ( str[i] == ')' )
            close[i] = close[i+1] + 1;
        else
            close[i] = close[i+1];
    }
  
    // check if there is no opening or closing
    // brackets
    if (open[len] == 0)
        return len;
    if (close[0] == 0)
        return 0;
  
    // check if there is any index at which
    // both brackets are equal
    for (int i=0; i<=len; i++)
        if (open[i] == close[i])
            index = i;
  
    return index;
}
  
// Driver code
int main()
{
    string str = "(()))(()()())))";
    cout << findIndex(str);
    return 0;
}


Java




// Java program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
  
public class GFG 
{
    // Method to find an equal index
    static int findIndex(String str)
    {
        int len = str.length();
        int open[] = new int[len+1];
        int    close[] = new int[len+1];
        int index = -1;
       
        open[0] = 0;
        close[len] = 0;
        if (str.charAt(0)=='(')
            open[1] = 1;
        if (str.charAt(len-1) == ')')
            close[len-1] = 1;
       
        // Store the number of opening brackets
        // at each index
        for (int i = 1; i < len; i++)
        {
            if ( str.charAt(i) == '(' )
                open[i+1] = open[i] + 1;
            else
                open[i+1] = open[i];
        }
       
        // Store the number of closing brackets
        // at each index
        for (int i = len-2; i >= 0; i--)
        {
            if ( str.charAt(i) == ')' )
                close[i] = close[i+1] + 1;
            else
                close[i] = close[i+1];
        }
       
        // check if there is no opening or closing
        // brackets
        if (open[len] == 0)
            return len;
        if (close[0] == 0)
            return 0;
      
        // check if there is any index at which
        // both brackets are equal
        for (int i=0; i<=len; i++)
            if (open[i] == close[i])
                index = i;
       
        return index;
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "(()))(()()())))";
        System.out.println(findIndex(str));
    }
}


Python3




# Method to find an equal index
def findIndex(str):
    l = len(str)
    open = [0] * (l + 1)
    close = [0] * (l + 1)
    index = -1
      
    open[0] = 0
    close[l] = 0
    if (str[0]=='('):
        open[1] = 1
    if (str[l - 1] == ')'):
        close[l - 1] = 1
      
    # Store the number of
    # opening brackets
    # at each index
    for i in range(1, l):
        if (str[i] == '('):
            open[i + 1] = open[i] + 1
        else:
            open[i + 1] = open[i]
      
    # Store the number
    # of closing brackets
    # at each index
    for i in range(l - 2, -1, -1):
        if ( str[i] == ')'):
            close[i] = close[i + 1] + 1
        else:
            close[i] = close[i + 1]
      
    # check if there is no 
    # opening or closing brackets
    if (open[l] == 0):
        return len
    if (close[0] == 0):
        return 0
      
    # check if there is any 
    # index at which both
    # brackets are equal
    for i in range(l + 1):
        if (open[i] == close[i]):
            index = i
      
    return index
      
# Driver Code
str = "(()))(()()())))"
print(findIndex(str))
  
# This code is contributed 
# by ChitraNayal


C#




// C# program to find an index 
// k which decides the number
// of opening brackets is equal 
// to the number of closing brackets
using System;
  
class GFG 
{
// Method to find an equal index
static int findIndex(string str)
{
    int len = str.Length;
    int[] open = new int[len + 1];
    int[] close = new int[len + 1];
    int index = -1;
  
    open[0] = 0;
    close[len] = 0;
    if (str[0] == '(')
        open[1] = 1;
    if (str[len - 1] == ')')
        close[len - 1] = 1;
  
    // Store the number of 
    // opening brackets
    // at each index
    for (int i = 1; i < len; i++)
    {
        if (str[i] == '(')
            open[i + 1] = open[i] + 1;
        else
            open[i + 1] = open[i];
    }
  
    // Store the number 
    // of closing brackets
    // at each index
    for (int i = len - 2; i >= 0; i--)
    {
        if (str[i] == ')')
            close[i] = close[i + 1] + 1;
        else
            close[i] = close[i + 1];
    }
  
    // check if there is no
    // opening or closing
    // brackets
    if (open[len] == 0)
        return len;
    if (close[0] == 0)
        return 0;
  
    // check if there is any
    // index at which both 
    // brackets are equal
    for (int i = 0; i <= len; i++)
        if (open[i] == close[i])
            index = i;
  
    return index;
}
  
// Driver Code
public static void Main()
{
    string str = "(()))(()()())))";
    Console.Write(findIndex(str));
}
}
  
// This code is contributed 
// by ChitraNayal


PHP




<?php
// Method to find an equal index
function findIndex($str)
{
    $len = strlen($str);
    $open = array(0, $len + 1, NULL);
    $close = array(0, $len + 1, NULL);
    $index = -1;
      
    $open[0] = 0;
    $close[$len] = 0;
    if ($str[0] == '(')
    $open[1] = 1;
    if ($str[$len - 1] == ')')
    $close[$len - 1] = 1;
      
    // Store the number 
    // of opening brackets
    // at each index
    for ($i = 1; $i < $len; $i++)
    {
        if ($str[$i] == '(')
            $open[$i + 1] = $open[$i] + 1;
        else
            $open[$i + 1] = $open[$i];
    }
      
    // Store the number 
    // of closing brackets
    // at each index
    for ($i = $len - 2; $i >= 0; $i--)
    {
        if ($str[$i] == ')')
        $close[$i] = $close[$i + 1] + 1;
        else
        $close[$i] = $close[$i + 1];
    }
      
    // check if there is no 
    // opening or closing
    // brackets
    if ($open[$len] == 0)
        return $len;
    if ($close[0] == 0)
        return 0;
      
    // check if there is any 
    // index at which both
    // brackets are equal
    for ($i = 0; $i <= $len; $i++)
        if ($open[$i] == $close[$i])
            $index = $i;
      
    return $index;
}
      
// Driver Code
$str = "(()))(()()())))";
echo (findIndex($str));
  
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
  
// Javascript program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
      
// Method to find an equal index
function findIndex(str)
{
    let len = str.length;
    let open = new Array(len + 1);
    let close = new Array(len + 1);
    for(let i = 0; i < len + 1; i++)
    {
        open[i] = 0;
        close[i] = 0;
    }
    let index = -1;
     
    open[0] = 0;
    close[len] = 0;
      
    if (str[0] == '(')
        open[1] = 1;
    if (str[len - 1] == ')')
        close[len - 1] = 1;
     
    // Store the number of opening brackets
    // at each index
    for(let i = 1; i < len; i++)
    {
        if (str[i] == '(')
            open[i + 1] = open[i] + 1;
        else
            open[i + 1] = open[i];
    }
     
    // Store the number of closing brackets
    // at each index
    for(let i = len - 2; i >= 0; i--)
    {
        if (str[i] == ')')
            close[i] = close[i + 1] + 1;
        else
            close[i] = close[i + 1];
    }
     
    // Check if there is no opening or closing
    // brackets
    if (open[len] == 0)
        return len;
    if (close[0] == 0)
        return 0;
    
    // Check if there is any index at which
    // both brackets are equal
    for(let i = 0; i <= len; i++)
        if (open[i] == close[i])
            index = i;
     
    return index;
}
  
// Driver Code
let str = "(()))(()()())))";
  
document.write(findIndex(str));
  
// This code is contributed by avanitrachhadiya2155
  
</script>


Output

9

Time Complexity: O(N), where N is the size of the given string
Auxiliary Space: O(N)

Approach 2: 

  • Count the total number of closed brackets in the string and store in a variable, let’s say cnt_close.
  • So count of open brackets is length of (string – count) of closed brackets.
  • Traverse string again but now keep count of open brackets in string, let’s say cnt_open.
  • Now while traversing, let index be i, so count of closed brackets till that index will be (i+1 – cnt_open).
  • Hence, we can check for what index, the count of open brackets in first part equals that of count of closed brackets in second part.
  • Equation becomes cnt_close – (i+1 – cnt_open) = cnt_open, we have to find i.
  • After evaluating above equation we can see cnt_open gets cancelled on both sides so no need.

Implementation:

C++




// C++ program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
#include <bits/stdc++.h>
using namespace std;
  
// Function to find an equal index
int findIndex(string str)
{
    // STL to count occurrences of ')'
    int cnt_close = count(str.begin(), str.end(), ')');
    for (int i = 0; str[i] != '\0'; i++)
        if (cnt_close == i)
            return i;
    // If no opening brackets
    return str.size();
}
  
// Driver code
int main()
{
    string str = "(()))(()()())))";
    cout << findIndex(str);
    return 0;
}
  
// This code is contributed by Dhananjay Dhawale @chessnoobdj


Java




// Java program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
  
public class GFG {
    // Method to find an equal index
    static int findIndex(String str)
    {
        int len = str.length();
        int cnt_close = 0;
        for (int i = 0; i < len; i++)
            if (str.charAt(i) == ')')
                cnt_close++;
        for (int i = 0; i < len; i++)
            if (cnt_close == i)
                return i;
        // If no opening brackets
        return len;
    }
  
    // Driver Method
    public static void main(String[] args)
    {
        String str = "(()))(()()())))";
        System.out.println(findIndex(str));
    }
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Method to find an equal index
def findIndex(str):
    cnt_close = 0
    l = len(str)
    for i in range(0, l):
        if(str[i] == ')'):
            cnt_close = cnt_close + 1
  
    for i in range(0, l):
        if(cnt_close == i):
            return i
    # If no opening brackets
    return l
  
  
# Driver Code
str = "(()))(()()())))"
print(findIndex(str))
  
# This code is contributed by Aditya Kumar (adityakumar129) and Sankararaman (sankararamank).


C#




using System;
  
// C# program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
public class GFG
{
  
  // Method to find an equal index
  public static int findIndex(String str)
  {
    var len = str.Length;
    var cnt_close = 0;
    for (int i = 0; i < len; i++) {
      if (str[i] == ')') {
        cnt_close++;
      }
    }
    for (int i = 0; i < len; i++) {
      if (cnt_close == i) {
        return i;
      }
    }
  
    // If no opening brackets
    return len;
  }
  
  // Driver Method
  public static void Main(String[] args)
  {
    var str = "(()))(()()())))";
    Console.WriteLine(findIndex(str));
  }
}
  
// This code is contributed by Aarti_Rathi


Javascript




<script>
  
// Javascript program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
      
// Method to find an equal index
function findIndex(str)
{
    let len = str.length;
    int cnt_close = 0;
    for(let i = 0; i < len; i++)
        if (str[i] == ')')
            cnt_close++;
           
     for(let i = 0; i < len; i++)
         if (cnt_close == i)
            return i;
        // If no opening brackets
        return len;
      
// Driver Code
let str = "(()))(()()())))";
  
document.write(findIndex(str));
  
// This code is contributed by Aditya Kumar (adityakumar129)
  
</script>


PHP




<?php
// Method to find an equal index
function findIndex($str)
{
    $len = strlen($str);
    $cnt_close = 0;
      for ($i = 1; $i < $len; $i++)
        if ($str[$i] == ')')
            $cnt_close ++;
        
      for ($i = 1; $i < $len; $i++)
        if ($cnt_close == $i)
              return $i;
      return $len;
}
      
// Driver Code
$str = "(()))(()()())))";
echo (findIndex($str));
  
// This code is contributed by Aditya Kumar (adityakumar129)
?>


Output

9

Time Complexity: O(N), Where N is the size of given string
Auxiliary Space: O(1)

Approach 3: (Solution in 1 iteration) 

  • Count the total number of closed brackets in string and store in variable, let’s say cnt_close.
  • So count of open brackets is length of (string – count) of closed brackets.
  • Traverse string again but now keep count of open brackets in string, let’s say cnt_open.
  • Now while traversing, let index be i, so count of closed brackets till that index will be (i+1 – cnt_open).
  • Hence, we can check for what index, the count of open brackets in first part equals that of count of closed brackets in second part.
  • Equation becomes cnt_close – (i+1 – cnt_open) = cnt_open, we have to find i.
  • After evaluating above equation we can see cnt_open gets cancelled on both sides so no need for the extra loop and simply return cnt_close.

C++




// C++ Program to implement above approach
#include<bits/stdc++.h>
using namespace std;
  
// Method to find an equal index
int findIndex(string str){
    int cnt_close = 0;
    int l = str.length();
    for(int i = 0; i<l; i++){
        if(str[i] == ')')
            cnt_close++;
    }
    return cnt_close;
}
  
int main(){
    string str = "(()))(()()())))";
    cout<<findIndex(str);
    return 0;
}
  
// This code is contributed by Yash Agarwal(yashagarwal2852002)


Java




// Java program to implement above approach
import java.util.*;
  
public class GFG {
    // Method to find an equal index
    static int findIndex(String str)
    {
        int cnt_close = 0;
        int l = str.length();
        for (int i = 0; i < l; i++) {
            if (str.charAt(i) == ')')
                cnt_close++;
        }
        return cnt_close;
    }
    public static void main(String[] args)
    {
        String str = "(()))(()()())))";
        System.out.println("OP: " + findIndex(str));
    }
}
  
// This code is contributed by Karandeep1234


Python3




# Method to find an equal index
def findIndex(str):
    cnt_close = 0
    l = len(str)
    for i in range(0, l):
        if(str[i] == ')'):
            cnt_close = cnt_close + 1
  
    return cnt_close
  
# Driver Code
str = "(()))(()()())))"
print(f"OP: {findIndex(str)}")
# This code is contributed by Sankararaman (sankararamank).


C#




// C# implementation of the above approach
  
using System;
using System.Collections.Generic;
  
class GFG {
  
  // Method to find an equal index
  static int findIndex(string str){
    int cnt_close = 0;
    int l = str.Length;
    for(int i = 0; i < l; i++){
      if(str[i] == ')')
        cnt_close++;
    }
    return cnt_close;
  }
  
  public static void Main()
  {
    string str = "(()))(()()())))";
    Console.Write("OP: "+findIndex(str));
  }
}
  
// This code is contributed by poojaagarwal2.


Javascript




// Javascript Program to implement above approach
  
// Method to find an equal index
function findIndex(str){
    let cnt_close = 0;
    let l = str.length;
    for(let i = 0; i<l; i++){
        if(str[i] == ')')
            cnt_close++;
    }
    return cnt_close;
}
  
    let str = "(()))(()()())))";
    document.write(findIndex(str));
     


Output

OP: 9

Time Complexity: O(N), Where N is the size of the given string
Auxiliary Space: O(1)

 



Similar Reads

Find time required to reach point N from point 0 according to given rules
Given two positive integers X and Y and N number of points arranged in a line, the task is to find the time required to reach point N from point 0 according to the following rules: Every point has one barrier that closes after every Y minutes and remains closed for the next Y minutes.On reaching a point if the barrier is closed, then the person nee
7 min read
Binary tree to string with brackets
Construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair "()". Omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree. Examples: Input : Preorder: [1,
8 min read
Balance a string after removing extra brackets
Given a string of characters with opening and closing brackets. The task is to remove extra brackets from string and balance it. Examples: Input: str = "gau)ra)v(ku(mar(rajput))" Output: gaurav(ku(mar(rajput))) Input: str = "1+5)+5+)6+(5+9)*9" Output: 1+5+5+6+(5+9)*9 Approach: Start traversing from left to right.Check if the element at current inde
6 min read
Remove brackets from an algebraic string containing + and - operators
Simplify a given algebraic string of characters, '+', '-' operators and parentheses. Output the simplified string without parentheses. Examples: Input : "(a-(b+c)+d)" Output : "a-b-c+d" Input : "a-(b-c-(d+e))-f" Output : "a-b+c+d+e-f" The idea is to check operators just before starting of bracket, i.e., before character '('. If operator is -, we ne
8 min read
Reflection of a point at 180 degree rotation of another point
Given two points coordinates (x1, y1) and (x2, y2)on 2D plane. The task is to find the reflection of (x1, y1) at 180 degree rotation of (x2, y2).Examples: Input : x1 = 0, y1 = 0, x2 = 1, y2 = 1 Output : (2, 2) Input : x1 = 1, y1 = 1, x2 = 2, y2 = 2 Output : (3, 3) Let the reflection point of point (x1, y1) about (x2, y2) be (x', y'). For (x', y') b
4 min read
Rotation of a point about another point
We have already discussed the rotation of a point P about the origin in the Set 1 and Set 2. The rotation of point P about origin with an angle ? in the anti-clockwise direction is given as under: Rotation of P about origin: P * polar(1.0, ?)Rotation of P about point Q Now, we have to rotate the point P not about origin but about a general point Q.
8 min read
Number of closing brackets needed to complete a regular bracket sequence
Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete the bracket sequence, print "IMPOSSIBLE". Let us def
7 min read
Balanced expressions such that given positions have opening brackets | Set 2
Given an integer n and an array of positions ‘position[]’ (1 <= length(position[]) <= 2n), find the number of ways of proper bracket expressions that can be formed of length 2n such that given positions have the opening bracket. Note: position[] array is given in the form of (1-based indexing) [0, 1, 1, 0]. Here 1 denotes the positions at whi
15+ min read
Print the balanced bracket expression using given brackets
Given four integers a, b, c and d which signifies the number of four types of brackets. "((""()"")(""))" The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. In case of multiple answers, print any one. Examples: Input: a = 3, b = 1, c = 4, d = 3 Output: (((
6 min read
Check if it is possible to obtain a Balanced Parenthesis by shifting brackets to either end at most K times
Given a string S of size N consisting of only '(' and ')' only and a positive integer K, the task is to check if the given string can be made a valid parenthesis sequence by moving any characters of the string S to either end of the string at most K number of times. Examples: Input: S = ")(", K = 1Output: YesExplanation: Move S[0] to the end of the
8 min read
Minimum swaps to balance the given brackets at any index
Given a balanced string of even length consisting of equal number of opening brackets ‘[‘ and closing brackets ‘]’ , Calculate the minimum number of swaps to make string balanced. An unbalanced string can be made balanced by swapping any two brackets. A string is called balanced if it can be represented in the form of "[S1]" where S1 is a balanced
5 min read
Print all Balanced Brackets Strings that can be formed by replacing wild card '?'
Given string str containing characters '?', '(' and ')', the task is to replace the '?' character with '(' or ')' and print all the strings containing balanced brackets Example: Input: str = "????"Output:()()(()) Input: str = "(()?"Output: (()) Approach: The given problem can be solved using recursion and backtracking. The idea is to substitute eve
10 min read
Javascript Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
Given an expression string exp, write a program to examine whether the pairs and the orders of "{", "}", "(", ")", "[", "]" are correct in exp. Example:  Input: exp = "[()]{}{[()()]()}" Output: Balanced Input: exp = "[(])" Output: Not Balanced  Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.   Algorithm:  Declar
2 min read
Balanced expressions such that given positions have opening brackets
Given an integer n and an array of positions 'position[]' (1 <= position[i] <= 2n), find the number of ways of proper bracket expressions that can be formed of length 2n such that given positions have opening bracket.Examples : Input : n = 3, position[] = [2}Output : 3 Explanation : The proper bracket sequences of length 6 and opening bracket
15 min read
Printing brackets in Matrix Chain Multiplication Problem
Prerequisite : Dynamic Programming | Set 8 (Matrix Chain Multiplication) Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. We have many options to multiply a chain of matrices b
15+ min read
Check if two expressions with brackets are same
Given two expressions in the form of strings. The task is to compare them and check if they are similar. Expressions consist of lowercase alphabets, '+', '-' and '( )'. Examples: Input : exp1 = "-(a+b+c)" exp2 = "-a-b-c" Output : Yes Input : exp1 = "-(c+b+a)" exp2 = "-c-b-a" Output : Yes Input : exp1 = "a-b-(c-d)" exp2 = "a-b-c-d" Output : No It ma
11 min read
Find a Fixed Point (Value equal to index) in a given array | Duplicates Allowed
Given an array of n integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in the array can be negative. Examples: Input: arr[] = {-10, -5, 0, 3, 7} Output
13 min read
Find Equal (or Middle) Point in a sorted array with duplicates
Given a sorted array of n size, the task is to find whether an element exists in the array from where the number of smaller elements is equal to the number of greater elements.If Equal Point appears multiple times in input array, return the index of its first occurrence. If doesn't exist, return -1. Examples : Input : arr[] = {1, 2, 3, 3, 3, 3} Out
9 min read
Find a Fixed Point (Value equal to index) in a given array
Given an array of n distinct integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, it returns -1. Fixed Point in an array is an index i such that arr[i] equals i. Note that integers in the array can be negative. Examples: Input: arr[] = {-10, -5, 0, 3, 7}Outpu
9 min read
Equation of straight line passing through a given point which bisects it into two equal line segments
Given a straight line which passes through a given point (x0, y0) such that this point bisects the line segment in two equal line segments. The task is to find the equation of this straight line.Examples: Input: x0 = 4, y0 = 3 Output: 3x + 4y = 24Input: x0 = 7, y0 = 12 Output: 12x + 7y = 168 Approach: Let PQ be the line and AB be the line segment b
4 min read
Maximum Fixed Point (Value equal to index) in a given Array
Given an array arr[] of size N, the task is to find the maximum index i such that arr[i] is equal to i. If there is no such index in the array arr[] then print -1. Examples: Input: arr[ ] = {-10, -5, 0, 3, 7}Output: 3Explanation: Only for i=3, arr[3] = 3 Input: arr[ ] = {0, 2, 5, 8, 4}Output: 4 Approach: Follow the steps below to solve this problem
4 min read
Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
Generate all permutations of a given length such that every permutation has more or equals 1's than 0's in all prefixes of the permutation. Examples: Input: len = 4 Output: 1111 1110 1101 1100 1011 1010 Note that a permutation like 0101 can not be in output because there are more 0's from index 0 to 2 in this permutation. Input: len = 3 Output: 111
5 min read
Count characters of a string which when removed individually makes the string equal to another string
Given two strings A and B of size N and M respectively, the task is to count characters of the string A, which when removed individually makes both the strings equal. If there exists several such characters, then print their respective positions. Otherwise, print "-1". Examples: Input: A = "abaac", B = "abac"Output: 2 3 4Explanation: Following remo
8 min read
Maximum point to convert string S to T by swapping adjacent characters
Given two strings S and T of length N, the task is to find the maximum points gained in converting the string S into string T by performing the following operation on string S: In one move, select an index i (1 â‰Ī i â‰Ī N−1), get (Si − Si + 1) points, and then swap Si and Si + 1Examples: Input: S = "321", T = "123"Output: 4â€ĻExplanation: One possible s
9 min read
Check if a given string is a valid number (Integer or Floating Point) | SET 1(Basic approach)
Validate if a given string is numeric. Examples: Input : str = "11.5" Output : true Input : str = "abc" Output : false Input : str = "2e10" Output : true Input : 10e5.4 Output : false The following cases need to be handled in the code. Ignore the leading and trailing white spaces.Ignore the '+', '-' and'.' at the start.Ensure that the characters in
11 min read
Check if a given string is a valid number (Integer or Floating Point) in Java
In the article Check if a given string is a valid number, we have discussed general approach to check whether a string is a valid number or not. In Java we can use Wrapper classes parse() methods along with try-catch blocks to check for a number. For integer number Integer class provides a static method parseInt() which will throw NumberFormatExcep
4 min read
Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)
In Set 1, we have discussed general approach to check whether a string is a valid number or not. In this post, we will discuss regular expression approach to check for a number. Examples: Input : str = "11.5" Output : true Input : str = "abc" Output : false Input : str = "2e10" Output : true Input : 10e5.4 Output : false Check if a given string is
3 min read
Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes positive for the first time. Since f() is monotonic
11 min read
Program to find the mid-point of a line
Given two coordinates of a line starting is (x1,y1) and ending is (x2,y2) find out the mid-point of a line. Examples : Input : x1 = –1, y1 = 2, x2 = 3, y2 = –6 Output : 1,–2 Input : x1 = 6.4, y1 = 3 x2 = –10.7, y2 = 4 Output : –2.15, 3.5 The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the point M found by the following fo
3 min read
Find the other end point of a line with given one end and mid
Given a midpoint of line(m1, m2) and one coordinate of a line (x1, y1), find the other end point(x2, y2) of a line. Examples: Input : x1 = –1, y1 = 2, and m1 = 3, m2 = –6 Output : x2 = 7, y2 = 10 Input : x1 = 6.4, y1 = 3 and m1 = –10.7, m2 = 4 Output : x2 = 3, y2 = 4 The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the poi
4 min read
Article Tags :
Practice Tags :