How to solve simple Java code on Code Monk

59 views Asked by At

I received below error while executing the code on Hacker Earth:

[Execution failed.

Stack Trace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at TestClass.Rotate(TestClass.java:25)
at TestClass.main(TestClass.java:62)](https://www.hackerearth.com/practice/codemonk/)

Program:

import java.util.*;

class TestClass {

    // Function to rotate array
    static void Rotate(int arr[], int d, int n) {
        // Storing rotated version of array
        int temp[] = new int[n];

        // Keeping track of the current index
        // of temp[]
        int k = 0;

        // Storing the n - d elements of
        // array arr[] to the front of temp[]
        for (int i = d+1; i < n-1; i++) {
            temp[k] = arr[i];
            k++;
        }

        // Storing the first d elements of array arr[]
        // into temp
        for (int i = 0; i < d+1; i++) {
            temp[k] = arr[i];
            k++;
        }

        // Copying the elements of temp[] in arr[]
        // to get the final rotated array
        for (int i = 0; i < n-1; i++) {
            arr[i] = temp[i];
        }
    }

    // Function to print elements of array
    static void PrintTheArray(int arr[], int n) {
        for (int i = 0; i < n-1; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();

        
        int k = sc.nextInt();

        int[] arr = new int[n];

       
        // Taking input for array elements
        for (int i = 0; i < n-1; i++) {
            arr[i] = sc.nextInt();
        }

        int N = arr.length;

        // Function calling
        Rotate(arr, k, N);

        // Printing the rotated array
        PrintTheArray(arr, N);
    }
}

How can I fix this error?

1

There are 1 answers

1
El Kamphy On

Consider adding debugging instructions before accessing your arrays. You can use System.out.println("i="+i") before accessing with index i and System.out.println("k="+k") with k. Print also the array length to make sure the index is within the range : System.out.println("size="+arr.length").

The problem is with these lines : temp[k] = arr[i]; k++;

At some point, k is 1 while the temp size is 1. The max value of k must then be 0.