forked from RyanFehr/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
49 lines (43 loc) · 1.99 KB
/
Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
Problem: https://www.hackerrank.com/challenges/circular-array-rotation/problem
C# Language Version: 6.0
.Net Framework Version: 4.5.2
Thoughts :
1. Let there be n numbers in an array a.
2. Let total number of rotations be k.
3. Get effective number of rotations using modulus. Let it be effectiveK. Set effectiveK to k % n.
4. Start iterating each query index one by one
4.1 Let query index be m
4.2 Subtract effective k from m to get original position of the element . Let's call it origP.
4.3 If origP is 0 or positive then print a[origP]
4.4 If origP is negative the print a[origP + n]
Time Complexity: O(m) //m is number of queries
Space Complexity: O(1) //number of dynamically allocated variables remain constant with increasing number of elements or queries.
*/
using System;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
var tokens_n = Console.ReadLine().Split(' ');
var numberOfElements = int.Parse(tokens_n[0]);
var numberOfRotations = int.Parse(tokens_n[1]);
//after every n rotations every element will come back to its original position which results in no movement.
//Remainder operator tells the precise movement.
var effectiveRotations = numberOfRotations % numberOfElements;
var numberOfQueries = int.Parse(tokens_n[2]);
var a_temp = Console.ReadLine().Split(' ');
var inputNumbers = Array.ConvertAll(a_temp, Int32.Parse);
for (int a0 = 0; a0 < numberOfQueries; a0++)
{
var m = int.Parse(Console.ReadLine());
//get the original position of the element before movement
var originalPosition = m - effectiveRotations;
if (originalPosition >= 0)
Console.WriteLine(inputNumbers[originalPosition]);
else //this means element must have got wrapped to the other end
Console.WriteLine(inputNumbers[originalPosition + numberOfElements]);
}
}
}