No results found for the specified position. Create a solution to return a rearranged a... Python Beginner Level Arrays Mock Interview

MockQuestions

Python Beginner Level Arrays Mock Interview

Question 2 of 12 for our Python Beginner Level Arrays Mock Interview

Get More Information About Our Python Beginner Level Arrays Interview Questions

Question 2 of 12

Create a solution to return a rearranged array.

This interview question concentrates on Python functions.

You are given array nums. It contains 2*n elements in form of-
[x1, x2, x3, …, xn, y1, y2, y3, …, yn]
Rearrange the given array to make in form of-
[x1, y1, x2, y2, x3, y3, …, xn, yn]
You have to return a solution in a new array.

/*Example*/

nums = [1,2,3,4,4,3,2,1], n = 4
expected = [1,4,2,3,3,2,4,1]

Solution:

We need to place the first n number to even indices (0-indexed) of the result array, and place next n elements to odd indices. This makes the solution pretty straightforward.

Create a new result array of size 2 * n. Copy first n number to even indices, that is 2 * I, and other n elements to odd indices, that is 2 * i + 1.

def shuffle(nums, n):
	result = [0] * 2 * n 

	for i in range(n):
		result[2 * i] = nums[i]       	# for even places
		result[2 * i + 1] = nums[i + n]  # for odd places

	return result

Time complexity- O(n)
Space complexity- O(n)

Written by on June 27th, 2021

Next Question

How to Answer: Create a solution to return a rearranged array.

Advice and answer examples written specifically for a Python Beginner Level Arrays job interview.

  • 2. Create a solution to return a rearranged array.

      This interview question concentrates on Python functions.

      You are given array nums. It contains 2*n elements in form of-
      [x1, x2, x3, …, xn, y1, y2, y3, …, yn]
      Rearrange the given array to make in form of-
      [x1, y1, x2, y2, x3, y3, …, xn, yn]
      You have to return a solution in a new array.

      /*Example*/
      
      nums = [1,2,3,4,4,3,2,1], n = 4
      expected = [1,4,2,3,3,2,4,1]

      Solution:

      We need to place the first n number to even indices (0-indexed) of the result array, and place next n elements to odd indices. This makes the solution pretty straightforward.

      Create a new result array of size 2 * n. Copy first n number to even indices, that is 2 * I, and other n elements to odd indices, that is 2 * i + 1.

      def shuffle(nums, n):
      	result = [0] * 2 * n 
      
      	for i in range(n):
      		result[2 * i] = nums[i]       	# for even places
      		result[2 * i + 1] = nums[i + n]  # for odd places
      
      	return result

      Time complexity- O(n)
      Space complexity- O(n)

      Written by S. Kumar on June 27th, 2021