07/29/16

# HackerRank ‘Circular Array Rotation’ Solution

##### 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:

[rust]
use std::io;

fn get_number() -> u32 {
let mut line = String::new();
line.trim().parse::<u32>().unwrap()
}

fn get_numbers() -> Vec<u32> {
let mut line = String::new();
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]);
}
}
[/rust]

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

07/29/16

# HackerRank ‘Compare Triplets’ Solution

##### Short Problem Definition:

Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100  for three categories: problem clarity, originality, and difficulty.

Compare Triplets

##### Complexity:

time complexity is O(1)

space complexity is O(1)

##### Execution:

This is a warmup. Follow specification.

##### Solution:

[rust]
use std::io;
use std::cmp::Ordering;

fn get_numbers() -> Vec<u32> {
let mut line = String::new();
line.split_whitespace().map(|s| s.parse::<u32>().unwrap()).collect()
}

fn main() {
let a = get_numbers();
let b = get_numbers();

let mut alice = 0;
let mut bob = 0;

for idx in 0..3 {
match a[idx].cmp(&b[idx]) {
Ordering::Less => bob += 1,
Ordering::Greater => alice += 1,
Ordering::Equal => {},
}
}

println!("{} {}", alice, bob);
}
[/rust]

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

07/3/16

# HackerRank ‘Divisible Sum Pairs’ Solution

##### Short Problem Definition:

You are given an array of n integers and a positive integer, k. Find and print the number of (i,j) pairs where i < j and ai + aj is evenly divisible by k.

Divisible Sum Pairs

##### Complexity:

time complexity is O(N^2)

space complexity is O(1)

##### Execution:

Brute force search.

##### Solution:
n,k = raw_input().strip().split(' ')
n,k = [int(n),int(k)]
a = map(int,raw_input().strip().split(' '))
count=0
for i in xrange(len(a)):
for j in xrange(i+1,len(a)):
if (a[i]+a[j]) % k == 0:
count+=1

print count


If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.