0
0
Javascriptprogramming~5 mins

Unary operators in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Unary operators
O(n)
Understanding Time Complexity

Unary operators perform simple actions on a single value. We want to see how their use affects the time it takes for code to run.

How does the number of unary operations grow as input size changes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
  numbers[i] = -numbers[i];
}
    

This code uses a unary minus operator to change each number to its negative inside a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Applying the unary minus operator to each element.
  • How many times: Once for each element in the array.
How Execution Grows With Input

Each element gets processed once, so the work grows directly with the number of elements.

Input Size (n)Approx. Operations
1010 unary operations
100100 unary operations
10001000 unary operations

Pattern observation: Doubling the input doubles the number of unary operations.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items.

Common Mistake

[X] Wrong: "Unary operators run instantly and don't add to time complexity."

[OK] Correct: Even simple operations take time, and when repeated many times, they add up proportionally to input size.

Interview Connect

Understanding how simple operations inside loops affect performance helps you explain code efficiency clearly and confidently.

Self-Check

"What if we replaced the unary minus with a function call inside the loop? How would the time complexity change?"