Grokking Data Structures & Algorithms for Coding Interviews

0% completed

Solution: Beautiful Array

Problem Statement

Given a positive integer N, construct a beautiful array of size N containing the number [1, N] .

An array beautiful if it follows the conditions below.

  • If for any three indices i, j, k (with i < j < k), A[j] * 2 is not equal to A[i] + A[k].

Examples

Example 1

  • Input: 4
  • Expected Output: [2, 1, 4, 3]
  • Justification: In this array, no combination of i, j, k (where i < j < k) exists such that 2 * A[j] = A[i] + A[k].

Example 2

  • Input: 3
  • Expected Output: [1, 3, 2]

.....

.....

.....

Like the course? Get enrolled and start learning!
S

shripadtheneo

· 2 years ago

class Solution: def beautifulArray(self, N: int) -> [int]: result = [0] * N if N == 1: return[1] print(result) for i in range(0, N, 2): if i+1 < N: result[i] = i+2 result[i+1] = i+1 else: result[i] = i+1 print(result) # ToDo: Write Your Code Here. return result
Show 1 reply