HackerRank 'Circular Array Rotation' Solution

Martin Kysel · July 29, 2016

Short Problem Definition:

John Watson performs an operation called a right circular rotation on an array of integers.

Circular Array Rotation

Complexity:

time complexity is O(Q)

space complexity is O(1)

Execution:

Calculate the offset for every query. Watch out for index overflows and negative modulo.

Solution:

use std::io;
 
fn get_number() -> u32 {
    let mut line = String::new();
    io::stdin().read_line(&mut line).ok().expect("Failed to read line");
    line.trim().parse::<u32>().unwrap()
}
 
fn get_numbers() -> Vec<u32> {
    let mut line = String::new();
    io::stdin().read_line(&mut line).ok().expect("Failed to read line");
    line.split_whitespace().map(|s| s.parse::<u32>().unwrap()).collect()
}
 
fn main() {
    let line = get_numbers();
    let (n,k,q) = (line[0], line[1], line[2]);
    let a = get_numbers();
    for _ in 0..q {
        let m = get_number();
        let idx = ((m-(k%n)+n)%n) as usize;
        println!("{}", a[idx]);
    }
}

Twitter, Facebook

To learn more about solving Coding Challenges in Python, I recommend these courses: Educative.io Python Algorithms, Educative.io Python Coding Interview.