Oracle Coding Interview

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-04-11Added By Anonymous
Source: Link

Company: Oracle
Role: unknown
Interview Stage: Phone Screen
Location: unknown
Year: unknown

Original Post Content:

Given a string - sequence of brackets, return the number of valid ways we can insert '(' to make the sequence of brackets as a valid.

Example:

Input : "(()())()" Output: 7
Input: "(()))" Output: 5

image

Better solutions are welcome :)

Time Complexity: O(n^2)

public class Solution {

	public static void main(String[] args) {
		System.out.println(countBracketSequence("(()())()"));// 7
		System.out.println(countBracketSequence("(()))"));// 5
	}

	public static int countBracketSequence(String s) {
		int total = 0;
		for (int i = 0; i < s.length(); i++) {
			StringBuffer sb = new StringBuffer(s);
			sb.insert(i, '(');
			if (isValidBracket(sb.toString())) {
				total++;
			}
		}
		return total;
	}

	public static boolean isValidBracket(String s) {
		Stack<Character> stack = new Stack<>();

		for (char c : s.toCharArray()) {
			if (c == '(') {
				stack.push(c);
			} else if (!stack.isEmpty() && c == ')' && stack.peek() == '(') {
				stack.pop();
			}
		}
		return stack.isEmpty();
	}
}

Comments