DEV Community

Cover image for 1389. Create Target Array in the Given Order(bruteForce)
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

1389. Create Target Array in the Given Order(bruteForce)

Introduction

Image description

Here our problem says, we are given 2 arrays and have to build a new array using those 2. So, in an array there is two part one is index and another one is value in that index. Here the our new array index and its value is separated in two other array one is nums which consist the index value and another one is index array where we have the index value of the new array.

Examples

Image description

Steps

  1. Take a for loop and set the index value to arrIndex and array_value to value
  2. Check if Same index is arrived before or not using isArrived Method.
  3. if true then run a for loop and swap the elements to it right from the index value.
  4. insert the value in the index.

Hints

Image description

JavaCode

class Solution {
    public int[] createTargetArray(int[] nums, int[] index) {
        int[] arr = new int [nums.length];
        int arrIndex = 0;
        int value = 0;

        for(int i = 0; i<nums.length; i++){
            arrIndex = index[i];
            value = nums[i];
            if(isAccess(index, arrIndex, nums.length)){
                for(int j = nums.length-2; j>= arrIndex; j-- )
                {
                    arr[j+1] = arr[j];
                }
            }
            arr[arrIndex] = value;
        }
        return arr;
    }
    public boolean isAccess(int []arr, int arrIndex, int length){
        for(int i = 0; i< length; i++){
            if(arr[i] == arrIndex){
                return true;
            }
        }
        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)