Bernard Wong
  • Software Engineer
  • Problems
    • Lowest Common Ancestor of a Binary Tree
    • Longest Substring Without Repeating Characters
    • Longest Palindromic Substring
    • Longest Common Prefix
    • Isomorphic Strings
    • Integer to Roman
    • Frog Jump
    • Find the Difference
    • Find k closest elements to a given value
    • Longest Common Subsequence
    • Binary Search Tree from Sorted Array
    • Balanced Binary Tree
    • Sort Using Two Stacks
    • O(1) Stack
    • k-th element to last of a LinkedList
    • Dedup LinkedList
    • Check Rotated String
    • Compress String by Character Count
    • Escape HTML whitespace
    • Check String Permutation
    • Unique String
    • Container With Most Water
    • 4 Sum
    • 3 Sum Closest
    • 3 Sum
    • 2 Sum
    • Maximum Subarray
    • Nested List Weight Sum
    • Palindrome Number
    • Pow(x, n)
    • Regular Expression Matching
    • Remove Nth Node From End of List
    • Reverse Integer
    • Roman to Integer
    • Rotate Array
    • Search a 2D Matrix
    • Shortest Word Distance
    • Two Sum III - Data structure design
    • Valid Parentheses
    • ZigZag Conversion
    • Quicksort
    • Add Two Numbers
    • Best Time to Buy and Sell Stock
    • Letter Combinations of a Phone Number
  • Data Structures
    • Heap
Powered by GitBook
On this page
  1. Problems

Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array

[1,2,3,4,5,6,7]

is rotated to

[5,6,7,1,2,3,4]

Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

def rotate(nums: Array[Int], k: Int) = {
  val r = k % nums.length
  reverse(nums, 0, nums.length - 1)
  reverse(nums, 0, r - 1)
  reverse(nums, r, nums.length - 1)
  nums
}

def reverse(nums: Array[Int], start: Int, end: Int): Array[Int] = {
  val diff = (end - start) / 2
  var tmp = 0
  for (i <- 0 until diff) {
    tmp = nums(start + i)
    nums(start + i) = nums(end - i)
    nums(end - i) = tmp
  }
  nums
}

/**
  * http://blog.thedigitalcatonline.com/blog/2015/05/13/99-scala-problems-16-20/#.V84U_ZMrJE5
  */
def rotate[A](n: Int, l: List[A]): List[A] = {
  val wrapn = if (l.isEmpty) 0 else n % l.length
  if (wrapn < 0) rotate(l.length + n, l)
  else l.drop(wrapn) ::: l.take(wrapn)
}

rotate(Array(1, 2, 3, 4, 5, 6, 7, 8, 9), 2)

PreviousRoman to IntegerNextSearch a 2D Matrix

Last updated 6 years ago