Grokking Data Structures & Algorithms for Coding Interviews
Vote

0% completed

Solution: Rotate an Array

Problem Statement

Given an integer array nums and an integer k, rotate the array to the right by k steps and return the result.

Examples

Example 1

  • Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3
  • Expected Output: [5, 6, 7, 1, 2, 3, 4]

Example 2

  • Input: nums = [-1, -100, 3, 99], k = 2
  • Expected Output: [3, 99, -1, -100]

Example 3

  • Input: nums = [1, 2, 3], k = 5
  • Expected Output: [2, 3, 1]

Two things to settle first

A rotation by the length changes nothing. Moving every element `n

.....

.....

.....

Like the course? Get enrolled and start learning!
Shubham Pokale

Shubham Pokale

· 5 days ago

The swap presented in the solution is more pythonic : a[i], a[j] = a[j], a[i] here is a more explicit version that is beginner friendly : while i < j: a[i], a[j] = a[j], a[i] i += 1 j -= 1
Show 1 reply

Reading Progress

0%


Vote for new content