# Codility ‘Nesting’ Solution

##### Short Problem Definition:

Determine whether given string of parentheses is properly nested.

Nesting

##### Complexity:

expected worst-case time complexity is O(N);

expected worst-case space complexity is O(1)

##### Execution:

Because there is only one type of brackets, the problem is easier than Brackets. Just check if there is always a opening bracket before a closing one.

##### Solution:
def solution(S):
leftBrackets = 0

for symbol in S:
if symbol == '(':
leftBrackets += 1
else:
if leftBrackets == 0:
return 0
leftBrackets -= 1

if leftBrackets != 0:
return 0

return 1

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

• Nico
• Yixuan Eric Wang

well, the interviewer may be more satisfied if you see this as a stack problem…
https://codility.com/demo/results/trainingKGS97C-SUC/

• http://www.martinkysel.com/codility-brackets-solution/ is a stack problem. This is more simple and requires no stack 🙂

• Yixuan Eric Wang

yeah, you are right
actually I met this simple question(part of a bigger problem) several days ago, I didn’t use the stack idea in the first place, and then the interviewer was like:”you haven’t heard about stack?”, LOL

• I haven’t actually ever gotten any of these tasks in an interview. I have only gotten stuff like “Implement a smart pointer” or “reverse a linked list”. I myself use some of these. Not many are suitable, as the candidate is not in the proper state of mind to come up with a clever solution. Some solutions took me days, not 5 minutes.