Left Rotate Array by K Places

Arrays Fundamentals Easy
  • Rotating an array by 'k' steps is a frequently used operation in digital signal processing, particularly in operations such as circular convolution and in implementing algorithms like FFT (Fast Fourier Transform)
  • This concept finds applications in many areas including data compression tools, image processing software, and audio signal processing tools
  • It is the fundamental operation that allows you to shift frames, process signals and handle buffers -- which is critical, for instance, when streaming video or audio

Given an integer array nums and a non-negative integer k, rotate the array to the left by k steps.

Examples:

Input: nums = [1, 2, 3, 4, 5, 6], k = 2

Output: nums = [3, 4, 5, 6, 1, 2]

Explanation: rotate 1 step to the left: [2, 3, 4, 5, 6, 1]

rotate 2 steps to the left: [3, 4, 5, 6, 1, 2]

Input: nums = [3, 4, 1, 5, 3, -5], k = 8

Output: nums = [1, 5, 3, -5, 3, 4]

Explanation: rotate 1 step to the left: [4, 1, 5, 3, -5, 3]

rotate 2 steps to the left: [1, 5, 3, -5, 3, 4]

rotate 3 steps to the left: [5, 3, -5, 3, 4, 1]

rotate 4 steps to the left: [3, -5, 3, 4, 1, 5]

rotate 5 steps to the left: [-5, 3, 4, 1, 5, 3]

rotate 6 steps to the left: [3, 4, 1, 5, 3, -5]

rotate 7 steps to the left: [4, 1, 5, 3, -5, 3]

rotate 8 steps to the left: [1, 5, 3, -5, 3, 4]

Input: nums = [1, 2, 3, 4, 5], k = 4

Constraints

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • 0 <= k <= 105

Hints

  • Split the array into two parts at index k: the first k elements and the rest. Then rearrange the two parts to place the second part before the first part.
  • Think about how you can achieve the rotation by reversing parts of the array rather than using extra space.

Company Tags

Reddit Docker Byju's Twilio Johnson & Johnson JPMorgan Chase Visa Shopify HashiCorp Flipkart Siemens Healthineers Teladoc Health Cerner Western Digital KPMG Goldman Sachs AMD Ubisoft McKinsey & Company Mastercard Oracle Robinhood Cloudflare Optum Roche TCS Cognizant Accenture Infosys Capgemini Wipro