Create Array of distinct parts the place odd listed parts are a number of of left neighbour


View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Given an integer N, the duty is to generate an array A[] of size N such that it satisfies the next situations for all 1 ≤ i ≤ N−1:

  • Ai is a number of of Ai-1 when i is odd
  • Ai will not be a number of of Ai-1 when i is even
  • All Ai are pairwise distinct
  • 1 ≤ Ai ≤ 2⋅N

Notice: If there are a number of solutions print any of them.

    Examples:

Enter: N = 4
Output: 3 6 4 8 

Rationalization:  [3, 6, 4, 8] is a sound array as a result of:
A1 = 3 is a number of of A2 = 6
A2 = 6 will not be a number of of A3 = 4
A3 = 4 is a number of of A4 = 8.

Enter: N = 6
Output: 4 8 5 10 6 12

Strategy: The issue will be solved primarily based on the next statement:

Observations:

Let x = N − ⌈N / 2⌉ + 1. Then, the next sequence is legitimate: [x, 2⋅x, x + 1, 2⋅(x + 1), x + 2, …]

  • It’s straightforward to see that the weather at odd indices are in rising order from x→N. Equally, the weather at even indices are in rising order from 2⋅x→2⋅N (from 2⋅x→2⋅(N − 1) when N is odd).
  • Then, 2⋅x = 2⋅(N − ⌈N / 2⌉ + 1) > N implies the units {x, x + 1, …, N} and {2⋅x, 2⋅(x + 1), …, 2⋅N} are disjoint. Subsequently, all parts of the above sequence are distinctive.
  • Ai is a number of of Ai-1 will be trivially verified to be true for all odd
    Ai will not be a number of of Ai-1 holds true for all even i.

Thus, the supplied sequence fulfills all necessities of the issue, and is due to this fact legitimate!

Comply with the under steps to unravel the issue:

  • Initialize a variable oddElement = (N / 2) + 1 for odd listed parts.
  • Initialize a variable evenElement = oddElement * 2 for even listed parts.
  • Traverse a loop from 1 until N on i:
    • If i is odd print oddElement.
      • Assign evenElement = oddElement * 2.
      • Increment the evenElement.   
    • Else print the evenElement.
       

Under is the implementation of the above strategy.

Java

  

import java.io.*;

import java.util.*;

  

public class GFG {

  

    

    public static void discover(int N)

    {

        int oddElement = N - (int)Math.ground(N / 2) + 1;

        int evenElement = 2 * oddElement;

  

        for (int i = 1; i <= N; i++) {

  

            

            if ((i % 2) != 0) {

                System.out.print(oddElement + " ");

                evenElement = 2 * oddElement;

                oddElement++;

            }

  

            

            else {

                System.out.print(evenElement + " ");

            }

        }

    }

  

    

    public static void important(String[] args)

    {

        int N = 4;

  

        

        discover(N);

    }

}

Time Complexity: O(N)
Auxiliary House: O(1)

Leave a Reply