File tree 1 file changed +74
-0
lines changed
Course 2 - Data Structures in JAVA/Lecture 3 - Time Complexity
1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ You have been given a random integer array/list(ARR) of size N. Write a function that rotates the given array/list by D elements(towards the left).
3
+ Note: Change in the input array/list itself. You don't need to return or print the elements.
4
+ Input format :
5
+ The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
6
+ First line of each test case or query contains an integer 'N' representing the size of the array/list.
7
+ Second line contains 'N' single space separated integers representing the elements in the array/list.
8
+ Third line contains the value of 'D' by which the array/list needs to be rotated.
9
+
10
+ Output Format :
11
+ For each test case, print the rotated array/list in a row separated by a single space.
12
+ Output for every test case will be printed in a separate line.
13
+
14
+ Constraints :
15
+ 1 <= t <= 10^4
16
+ 0 <= N <= 10^6
17
+ 0 <= D <= N
18
+ Time Limit: 1 sec
19
+
20
+ Sample Input 1:
21
+ 1
22
+ 7
23
+ 1 2 3 4 5 6 7
24
+ 2
25
+ Sample Output 1:
26
+ 3 4 5 6 7 1 2
27
+
28
+ Sample Input 2:
29
+ 2
30
+ 7
31
+ 1 2 3 4 5 6 7
32
+ 0
33
+ 4
34
+ 1 2 3 4
35
+ 2
36
+ Sample Output 2:
37
+ 1 2 3 4 5 6 7
38
+ 3 4 1 2
39
+ */
40
+
41
+
42
+ public class RotateArray {
43
+
44
+ public static void rotate (int [] arr , int d ) {
45
+ //Your code goes here
46
+ if (d >0 )
47
+ {
48
+ d =d %(arr .length );
49
+ int [] temp =new int [d ];
50
+ for (int i =0 ;i <d ;i ++)
51
+ {
52
+ temp [i ]=arr [i ];
53
+ //System.out.print(temp[i]+" ");
54
+ }
55
+
56
+ //System.out.println();
57
+
58
+ for (int i =0 ,j =0 ;i <arr .length &&j <d ;i ++)
59
+ {
60
+ if (i >=(arr .length -d ))
61
+ {
62
+ arr [i ]=temp [j ];
63
+ j ++;
64
+ }
65
+ else
66
+ {
67
+ arr [i ]=arr [(i +d )%arr .length ];
68
+ }
69
+ }
70
+ }
71
+
72
+ }
73
+
74
+ }
You can’t perform that action at this time.
0 commit comments