BackmediumArraysCred

Galactic Transmission Solution

Problem Statement

You are given an integer array nums and a non‑negative integer k representing the number of cosmic events that must be performed. Two types of events are available: * Pulsar – sorts the current array in non‑decreasing order. * Blackhole – multiplies every element of the current array by -1. You may choose any event for each of the k steps and may repeat events. After exactly k steps output the lexicographically smallest possible array. An array a is lexicographically smaller than b if at the first index i where they differ a[i] < b[i].

Example 1
Input
nums = [3, -1, 2] k = 1
Output
[-1,2,3]

Explanation: Only one event can be applied. Using a Pulsar sorts the array to [-1,2,3], which is lexicographically smaller than applying a Blackhole (which would give [-3,1,-2]).

Example 2
Input
nums = [5, -4, 0] k = 2
Output
[-5,0,4]

Explanation: With two events we can obtain three distinct outcomes: 1. Pulsar then Pulsar → sort([5,-4,0]) = [-4,0,5] 2. Blackhole then Pulsar → sort([-5,4,0]) = [-5,0,4] 3. Pulsar then Blackhole → -sort([5,-4,0]) = [4,0,-5] The smallest lexicographically is [-5,0,4].

Example 3
Input
nums = [1,2,3] k = 3
Output
[-3,-2,-1]

Explanation: Three events allow the following candidates: - Original array after three Blackholes → [-1,-2,-3] - Sort after any Pulsar → [1,2,3] - Sort after an odd number of Blackholes → sort([-1,-2,-3]) = [-3,-2,-1] - Negative of a sorted array → [-1,-2,-3] The lexicographically smallest is [-3,-2,-1].

Example 4
Input
nums = [-7, 4, -2, 9] k = 4
Output
[-9,-4,2,7]

Explanation: Four events give enough freedom to choose any parity of sign flips before the final sort. The best choice is to apply an odd number of Blackholes before the last Pulsar, turning the array into [7,-4,2,-9] and then sorting to [-9,-4,2,7].

Constraints

  • 1 <= nums.length <= 100000
  • -1000000000 <= nums[i] <= 1000000000
  • 0 <= k <= 1000000000
  • All operations must be performed exactly k times
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Galactic Transmission — Problem Statement & Solution Guide

ArraysMediumcyclicity and pattern recognition
TimeO(n log n)
|
SpaceO(n)

Problem Description

You are given an integer array nums and a non‑negative integer k representing the number of cosmic events that must be performed. Two types of events are available:

* Pulsar – sorts the current array in non‑decreasing order.

* Blackhole – multiplies every element of the current array by -1.

You may choose any event for each of the k steps and may repeat events. After exactly k steps output the lexicographically smallest possible array. An array a is lexicographically smaller than b if at the first index i where they differ a[i] < b[i].

DSA Pattern Breakdown

DSA Pattern Breakdown

"Galactic Transmission"

medium

WHY DOES IT MATTER?

Understanding how global, order‑independent operations collapse the state space is crucial for many optimization problems, especially those involving batch transformations in large‑scale data pipelines.

OPTIMIZATION CHALLENGE

The insight that sorting erases all prior ordering and that sign flips are modulo‑2 reduces an exponential search to a constant‑time decision between two sorted arrays, cutting time from O(2^k·n) to O(n log n).

REAL-WORLD CONNECTION

Think of a distributed log that can be compacted (sorted) and mirrored (sign‑flipped). Regardless of how many times you compact or mirror, the final observable state is determined by whether you mirrored an odd or even number of times and whether you compacted at the end.

When faced with multiple global operations, always ask: does the operation commute or overwrite previous work? If it does, you can often reorder or discard steps to simplify the algorithm.

COMPLEXITY AT A GLANCE

⏱ Time:O(n log n)
💾 Space:O(n)

Core Theory — Why This Approach?

The problem reduces to a combinatorial reachability question on arrays under two global operations: full sort and global sign flip. A naive view might try to simulate all 2^k sequences, which explodes even for modest k because each step can be either operation, leading to exponential time. The key observation is that sorting is idempotent and order‑agnostic – applying it at any point reorders the entire array into non‑decreasing order, erasing any previous ordering information. Likewise, the Blackhole operation is also idempotent modulo two: applying it twice restores the original signs, so only the parity of Blackhole applications matters. By decoupling order from sign, the state space collapses to at most two distinct sorted configurations: the sorted original array and the sorted negated array. The optimal paradigm is therefore a greedy reduction to these two candidates, followed by a lexicographic comparison, which runs in O(n log n) time due to sorting.

Interview Questions on This Problem

Q1How would you determine the lexicographically smallest array after exactly k operations when both sorting and sign‑flip are allowed?

Observe that sorting can be deferred to the last step, and only the parity of sign‑flips matters. For k≥2 you can achieve both parity choices and a final sort, so compute sorted(nums) and sorted(‑nums) and pick the smaller lexicographically. Handle k=0 and k=1 as special cases.

Q2Why does the Blackhole operation only affect the final answer through its parity, and how does that simplify the solution?

Each Blackhole multiplies every element by –1. Two consecutive Blackholes multiply by (‑1)*(‑1)=1, restoring original signs. Hence any sequence of Blackholes is equivalent to either 0 or 1 effective flips, reducing the exponential possibilities to just two sign states.

Q3In a system where you can reorder data and invert its sign, what is the minimal set of states you need to consider to answer any query about the final ordering?

Only the sorted version of the original data and the sorted version after a single sign inversion. All other sequences either produce one of these two sorted arrays or an unsorted version that is never lexicographically optimal when a sort is available.

Examples

Example 1

Input

nums = [3, -1, 2]
k = 1

Output

[-1,2,3]

Explanation: Only one event can be applied. Using a Pulsar sorts the array to [-1,2,3], which is lexicographically smaller than applying a Blackhole (which would give [-3,1,-2]).

Example 2

Input

nums = [5, -4, 0]
k = 2

Output

[-5,0,4]

Explanation: With two events we can obtain three distinct outcomes: 1. Pulsar then Pulsar → sort([5,-4,0]) = [-4,0,5] 2. Blackhole then Pulsar → sort([-5,4,0]) = [-5,0,4] 3. Pulsar then Blackhole → -sort([5,-4,0]) = [4,0,-5] The smallest lexicographically is [-5,0,4].

Example 3

Input

nums = [1,2,3]
k = 3

Output

[-3,-2,-1]

Explanation: Three events allow the following candidates: - Original array after three Blackholes → [-1,-2,-3] - Sort after any Pulsar → [1,2,3] - Sort after an odd number of Blackholes → sort([-1,-2,-3]) = [-3,-2,-1] - Negative of a sorted array → [-1,-2,-3] The lexicographically smallest is [-3,-2,-1].

Example 4

Input

nums = [-7, 4, -2, 9]
k = 4

Output

[-9,-4,2,7]

Explanation: Four events give enough freedom to choose any parity of sign flips before the final sort. The best choice is to apply an odd number of Blackholes before the last Pulsar, turning the array into [7,-4,2,-9] and then sorting to [-9,-4,2,7].

Constraints

  • 1 <= nums.length <= 100000
  • -1000000000 <= nums[i] <= 1000000000
  • 0 <= k <= 1000000000
  • All operations must be performed exactly k times

Optimal Approach & Strategy

Compute the sorted original array and the sorted negated array, then return the lexicographically smaller; special‑case k=0 and k=1 where a sort may not be possible.

Brute Force Approach

Simulate every possible sequence of k events, applying sort or sign‑flip at each step, and keep the smallest resulting array.

Verified Code Solutions

JavaScript Solution
Time: O(n log n)
/**
 * @param {number[]} nums - The input array of integers
 * @param {number} k - The number of cosmic events to perform
 * @return {number[]} - The lexicographically smallest array after exactly k steps
 */
function galacticTransmission(nums, k) {
    if (nums.length === 0) return [];
    
    // Sort the array initially
    const sortedOriginal = [...nums].sort((a, b) => a - b);
    
    // If k is 0, return the sorted array
    if (k === 0) return sortedOriginal;
    
    // Create the negated and sorted array
    const negated = nums.map(x => -x);
    const sortedNegated = [...negated].sort((a, b) => a - b);
    
    // Compare the two candidates lexicographically
    // We can use the fact that arrays can be compared element by element
    for (let i = 0; i < sortedOriginal.length; i++) {
        if (sortedOriginal[i] < sortedNegated[i]) {
            return sortedOriginal;
        } else if (sortedOriginal[i] > sortedNegated[i]) {
            return sortedNegated;
        }
    }
    
    // If they are equal, return either one
    return sortedOriginal;
}

// Example usage
const nums = [3, -1, 2];
const k = 1;
const result = galacticTransmission(nums, k);
console.log(JSON.stringify(result));

Asked in Top Tech Interviews

Cred

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.