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
ortac
.tic
should not be immediate neighbour of itself.- The first
tic
must occur only whentac
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
There are these problems with your regex:
$
Here is a regex that does the job:
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.
^(tac|tictac)+(tac){2,}tictac(tac|tac|^)
test it here