skip to Main Content

I’m working on a code challenge from hackerrank and wonder why my solution failed on this task. (https://www.hackerrank.com/challenges/forward-references/problem)

Task

You have a test string 𝑆.

Your task is to write a regex which will match S, with following condition(s):

  • 𝑆 consists of tic or tac.
  • tic should not be immediate neighbour of itself.
  • The first tic must occur only when tac has appeared at least twice before.

My solution is

const currentLine = readLine();
const reg = /^(tac){2,}(tic)(1{1,}2{1}){0,}/
console.log(reg.test(currentLine));

I’ve failed on one test case — "tactactactictactictic".

The answer should be false since the last two "tic" don’t meet the second requirement.

In my regex, I thought this part — (1{1,}2{1}){0,} — already handled this scenario.
Unless there’s at least one tac before tic, else, should return false.
But the truth is, it’s returning true.

Can anyone help explain why my regex is wrong?

2

Answers


  1. There are these problems with your regex:

    • It does not require the whole input to match, which is why you got a false positive on that example input. You should assert the end of the input with $
    • It requires that the input includes at least one occurrence of "tic", but that is a too strong requirement. The occurrence of "tic" should be optional. For instance, "tac", "tactac" and "tactactac" are all valid inputs which your regex rejects.
    • It requires that the match ends with "tic", but this should not be mandatory. For instance, "tactactictac" is a valid input.

    Here is a regex that does the job:

    ^(tac)(?:1+(tic))*1*$
    

    See it on regex101

    Note that it does not match an empty input string. This is open for interpretation when the task says "𝑆 consists of tic or tac". Anyway, the tests on HackerRank do not include a test with an empty input string.

    Login or Signup to reply.
    1. start and the end of the string anchors (^$)
    2. first group (tac|tictac)+
    3. second group: (tac){2,}
    4. literal "tictac"
    5. last group (tac|tac|^)

    ^(tac|tictac)+(tac){2,}tictac(tac|tac|^)

    test it here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search