0

When I trying to solve LeetCode's task "Rotate Array" I have an error "Time Limit Exceeded", because on one of the task's test cases checkings I have following input: list named "sums" with 100k items and "k" variable = 54944.

The task description: "Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.".

My solution's code on python v. 2:

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        c = 0
        c_max = k - 1
        nums.reverse()
        while c <= c_max:
            nums.append(nums[0])
            del nums[0]
            c = c + 1
        nums.reverse()

How I should optimize this code to resolve the error?

  • 4
    If you have an input list with 3 entries, and you are asked to rotate it 1000 times, are you really going to do that action 1000 times, or do you see a shortcut somewhere? – trincot May 03 '23 at 20:08
  • Hint: every `for` loop and every `.reverse()` are an iteration over the entire data structure. With that in mind, take a look at Python’s concept of [iterators](https://wiki.python.org/moin/Iterator) and think about getting rid of entire iterations. – Jens May 03 '23 at 20:10
  • You should be able to solve this without loops or reversing the array. Study up on Python's list slicing feature. [How slicing in python works](https://stackoverflow.com/q/509211) – 001 May 03 '23 at 20:40
  • 1
    If you have an array of `k` items, no matter how many times you rotate it, there are only `k` possible outputs. Ex: `[1,2,3] -> [1,2,3] or [3,1,2] or [2,3,1]`. Rotate it one more time and you're back to `[1,2,3]`. – 001 May 03 '23 at 20:45

0 Answers0