Sabbir Ahmed
Sabbir Ahmed

Reputation: 1317

hacker rank compiler shows error when string length function input is modified

My code produces satisfied result in hacker rank compiler window for eleven out of fifteen test input in a certain problem. However, when i make subtle change in my code, all the the test inputs are run as OK.

This is a snippet of my previous code which shows error (terminated due to timeout).

for ind, letter in enumerate(string):
    if letter in vowels:
        kevin += len(string[ind:])
    else:
        stuart += len(string[ind:])

When i changed the above code as below all inputs are run successfully.

for ind, letter in enumerate(string):
    if letter in vowels:
        kevin += len(string) - ind
    else:
        stuart += len(string) - ind

Aren't these two codes equivalent?

Upvotes: 2

Views: 600

Answers (1)

Bharel
Bharel

Reputation: 26941

These code snippets are entirely equivalent apart from two things:

  1. Second one is more optimized - There are no multiple subset creations of string.
  2. Second one works for any collection - can work on dict, list, tuple, string and anything that implements both __len__ and __iter__.

As you've added the error, saying it's a timeout error, I'm leaning towards issue #1 which is the string creation.

If you're creating a subset of a very long string you do the following operations for each iteration:

  1. Allocate n-1 bytes of space. (Slowish)
  2. Set all that space to zero (done internally, probably using calloc())
  3. Copy n-1 bytes from the original string to that new space. (Slow)
  4. Find out the length (A very fast operation)
  5. Deallocate the space. (Fast as well)

For long strings, this whole sequence can be a heavy operation, especially done for every iteration.

Second algortithm does this:

  1. Get length (fast operation)
  2. Substract integer (fast operation)
  3. ???
  4. Profit.

Upvotes: 2

Related Questions