“Hacking” a Hackerrank problem using Python Basics.
This is a story about how I leveraged some of the Python’s lesser known capabilities to my advantage in solving a regular expression problem in a rather esoteric way (as we’ll see) on a popular coding platform called Hackerrank.
It’s been 5 years since and I think I can finally come out of the closet and reveal to the world what I did that day.
Year 2016, January. The 7th.
I was in the third year of my Computer Science undergrad when I came across the Regular Expresso challenge on Hackerrank. I found it intriguing that I had to solve a set of 8 regular expression challenges under an hour.
Folks not familiar with regex can read about it here.
I equipped myself with my then favourite programming language, Python to be able to complete the task.
Fast forward 5 questions and I’m blazing through the contest in no time.
Enter the 6th question, the Match Maker. This was labelled as Hard.
The full question can be found here.
The challenge talked about how we had to write a regex that had to match all of these (insert a list of words) and none of these (another list of words). The core constraint was that the length of the regular expression we write cannot exceed 60.
This, the platform validated using the below stub which we couldn’t override.
The challenge to the problem was to first, find the regular expression and then (second) optimize it to a minimum length.
I did find a regex but the length was exceeding 60.
After struggling for 30 minutes with the time running out, I thought I’d try to game the system. I knew the Hackerrank stub checks that the length of my input using the
len() and discards it if it is greater than 60 right away.
len() is an inbuilt function on the Python module
If only I could modify the logic that aims to find the length of a string
It hit me that in Python, you can override even the in built functions. This I thought was pure golden and evil while I was reading through its documentation back in the day.
I decided that I will override the
len() function to always return a number that is
less than or equal to 60. This way, I hoped I’d pass the stub validation as it only checks if the length is
greater than 60
""" An evil implementation that is only aimed to pass the test"""
And I did xD
I pressed submit and then to (not) my surprise all the tests passed.
How Hackerrank could have avoided this?
Well, for starters, detect overrides of built in functions, maybe?
These would now belong to a different module than
I went on to solve one more problem in the challenge but the joy I experienced in Problem #6 surpassed it all.
So, that’s all folks. The takeaway is that Reading documentation helps.
Hope you all enjoyed this piece.