Swapping Array Elements With Efficiency

Swapping Array Elements With Efficiency

BackerLeader 8 58 103
calendar_todayschedule1 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.



2 Comments

2 votes
1
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

MCP Is the USB-C of AI. So Why Are You Plugging Everything In?

Ken W. Algerverified - Jun 10

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

Most Candidates Memorize Merge Intervals. Few Actually Understand It.

yogirahul - May 21

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

Cláudio Raposo - May 5
chevron_left
6.9k Points170 Badges
Indiayogicode.org
35Posts
97Comments
7Connections
AI Engineer focused on building applications & writing practical guides on coding and machine learning.

Related Jobs

View all jobs →

Commenters (This Week)

5 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!