Swapping Array Elements With Efficiency

Swapping Array Elements With Efficiency

BackerLeader posted 1 min read

Most people think this is a “simple” problem.

Reverse an array.

But there are actually two very different ways to think about it


Approach 1: Let Python do the work

arr[::-1]

That’s it.

Looks clean. Works instantly.

But under the hood:

  • In a Python list, this creates a new array
  • It walks from end → start and copies elements

Time: O(n)
Space: O(n)

One interesting twist:

  • In NumPy, slicing often gives a view, not a full copy
    → same code, very different memory behavior

Approach 2: Swap from both ends

left, right = 0, len(arr) - 1

while left < right:
    arr[left], arr[right] = arr[right], arr[left]
    left += 1
    right -= 1

Here you’re not creating anything new.

Just swapping:

  • first ↔ last
  • then moving inward

Time: O(n)
Space: O(1)


What this really shows

Both solve the same problem.

But one is:

“just get it done”

The other is:

“do it with control”

And honestly, both are useful, depends on what you care about in that moment.


Small takeaway

Sometimes the difference in solutions isn’t about correctness.

It’s about:

  • how much you understand
  • and how much you care about what’s happening underneath

Next time something feels “too easy”…
there’s probably a deeper layer sitting right below it.



1 Comment

2 votes
1

More Posts

Dashboard Operasional Armada Rental Mobil dengan Python + FastAPI

Masbadar - Mar 12

I Wrote a Script to Fix Audible's Unreadable PDF Filenames

snapsynapseverified - Apr 20

Implementing Cellular Redundancy: Cross-Cloud Failover with AWS Transit Gateway and Azure ExpressRou

Cláudio Raposo - May 5

LeetCode AI Assistant: A Smarter Way to Prepare for Coding Interviews

Alex Hunter - Oct 9, 2025

Title: Boost Your Productivity with a Python Pomodoro Timer

Sami - Sep 25, 2025
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!