DEV Community

Cover image for 1470. Shuffle the Array(easy)
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

1470. Shuffle the Array(easy)

Introduction

Image description

Here we have given an and all we have to do is shuffle the array. So the procedure is we have to separate the array in two parts from the middle and n is the middle point and the array is always have event number of index. Now we have to take element from the each array put it in serial. Like we have nums = [2,5,1,3,4,7], n = 3. Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].

Examples

Image description

Image description

Steps

  1. take a new array arr having same length of nums
  2. Run for loop, from 0 to n;
  3. Now in even position put, arr[2*i] = nums[i];
  4. In odd position, arr[2*i+i] = nums[n + i];

Java Code1:

class Solution {
    public int[] shuffle(int[] nums, int n) {
        int [] arr = new int[n*2];
        for(int i = 0; i < n; i++){
            arr[2*i] = nums[i];
            arr[2*i + 1] = nums[n + i];
        }
        return arr;
    }
}
Enter fullscreen mode Exit fullscreen mode

Java Code2:

class Solution {
    public int[] shuffle(int[] nums, int n) {
        int[] ans = new int[2*n];
        int start = 1, end = n, i = 1;
        ans[0] = nums[0];
        while( i < 2*n){
            if( i % 2 != 0) {
                ans[i] = nums[end];
                end++;
            }
            else{
                ans[i] = nums[start];
                start++;
            }
            i++;
        }
        return ans;
    }
}
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.