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)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.