1. Permutation Verification (Brute Force)
Intuition
Generate permutations and check all (i, k, j) triplets for the forbidden arithmetic mean condition.
Algorithm
- 1. Create array [1, 2, ..., N].
- 2. For each permutation of the array: - Check all triplets i < k < j: - If 2*nums[k] == nums[i] + nums[j], fail. - If no triplet fails, return permutation.
Brute Force All Permutations Arithmetic Check
2 of 2 questions left todayPhase 1 — Step 1: Step 1: Permutation [1, 2, 3, 4] contains arithmetic progression 1, 2, 3 because 2 2 == 1 + 3
Phase 1 — Step 1: Step 1: Permutation [1, 2, 3, 4] contains arithmetic progression 1, 2, 3 because 2 * 2 == 1 + 3. Fails the beauty condition.
#include <iostream>#include <vector>#include <numeric>#include <algorithm>using namespace std; // Brute Force Approach: Permutation Verificationbool isValid(const vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; i++) { for (int k = i + 1; k < n; k++) { for (int j = k + 1; j < n; j++) { if (2 * nums[k] == nums[i] + nums[j]) { return false; } } } } return true;} vector<int> beautifulArray(int n) { vector<int> nums(n); iota(nums.begin(), nums.end(), 1); do { if (isValid(nums)) return nums; } while (next_permutation(nums.begin(), nums.end())); return {};} int main() { int n = 4; vector<int> result = beautifulArray(n); cout << "Output: ["; for (int i = 0; i < result.size(); i++) { cout << result[i] << (i + 1 < result.size() ? ", " : ""); } cout << "]" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N! * N^3)— There are N! permutations, and checking triplets takes O(N3) time. - Space complexity:
O(N)— Array of size N.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.