Skip to content

Mistake in test case Question #230 #331

Description

@Eghizio

There is a mistake in this question.

image

It is written that "{dklf(df(kl))d]{}" is a valid test case while it is not due to the not opened "[".

Please update the question.

The code I used to test the cases:

const sum = (arr: number[]): number => arr.reduce((acc, el) => acc+el, 0);

type OpeningBracket = "(" | "[" | "{";
type BracketStackMap = Record<OpeningBracket, number>;

const checkBrackets = (str: string) => {
  const brackets = ["(",")", "[","]", "{","}"]; // "()[]{}".split("");
  
  const filtered = str.split("").filter(character => brackets.includes(character));
  const bracketsStack = new Map<BracketStackMap>([["(", 0], ["[", 0], ["{", 0]]);

  for(let i=0; i<filtered.length; i++){
    // could be simplified with closed/opening bracket key/value mapping
    const key = filtered[i] === ")" ? "("
          : filtered[i] === "]" ? "["
          : filtered[i] === "}" ? "{"
          : filtered[i];
    
    const currentVal = bracketsStack.get(key);
    
    // console.log({i, str: filtered[i], key})
    
    switch(filtered[i]){
      case "(":
      case "[":
      case "{":
        bracketsStack.set(filtered[i], currentVal + 1);
        break;
      case ")":
      case "]":
      case "}":
        bracketsStack.set(key, currentVal - 1);
        break;
      default: throw new Error(`Unhandled bracket: ${filtered[i]}`);
    }
    
    if(bracketsStack.get(key) < 0){
      // console.log("negative", bracketsStack.get(key))
      return false;
    };
  }
  
  return (sum([...bracketsStack.values()]) === 0);
};

const tests = {
  "{ac[bb]}": true, 
  "{dklf(df(kl))d]{}": true, //fails, should pass according to task description
  "{[[[]]]}": true,
  "{3234[fd": false,
  "{df][d}": false
};

Object.entries(tests).forEach(([test, expected]) => {
  const result = (checkBrackets(test) === expected) ? "✅" : "❌";
  
  console.log(`${result} "${test}" `);
});
// results
"✅ '{ac[bb]}' "
"❌ '{dklf(df(kl))d]{}' "
"✅ '{[[[]]]}' "
"✅ '{3234[fd' "
"✅ '{df][d}' "

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions