Find the K-th Largest or Smallest in O(n) using nth_element | Competitive Programming Hack
Hello all, welcome to DSA Shorts with MIK - 12 🎥 ✨
Want to find the n-th largest or smallest element in an array without fully sorting it? 😎
Use nth_element() in C++ and do it in O(n) time! ⚡
In this short, we find the 2nd largest element using a simple, powerful STL function — no full sort, just a smart trick! 🔥
✅ What is nth_element()?
It partially sorts your array so that the element at the n-th position is in its correct place — all elements before it are smaller, and all after are greater (not necessarily sorted).
📌 Syntax:
nth_element(begin(v), begin(v) + idx, end(v));
This puts the element at index idx in its correct position, in O(n) time.
🔧 Perfect for competitive programming when you're short on time but need precision!
Add this STL gem to your toolkit and code smarter. 🚀
📚 My DP Concepts Playlist: • Roadmap for DP | How to Start DP ? | ...
📚 My Graph Concepts Playlist: • Graph Concepts & Qns - 1 : Graph will...
📚 Segment Tree: • Segment Tree | Introduction | Basics ...
📚 Recursion: • Introduction | Recursion Concepts And...
📚 Trie: • Word Search II (Google, Amazon, Meta,...
📚 Difference Array Technique: • Introduction | What | How | Differenc...
🔗 GitHub Interview Prep Rephttps://github.com/MAZHARMIK/Interview_DS_Algo...
📸 Instagrahttps://www.instagram.com/codestorywithmik/k
📘 Faceboohttps://www.facebook.com/people/codestorywithmik/100090524295846/6
🐦 Twittehttps://twitter.com/CSwithMIKk
🔔 Subscribe: / @codestorywithmik
╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
╠╗║╚╝║║╠╗║╚╣║║║║║═╣
╚═╩══╩═╩═╩═╩╝╚╩═╩═╝
#DSA #CodingTips #nth_element #CompetitiveProgramming
#LearnWithMIK #codestorywithmik #shorts #cpp #nthsimplified
#dsa #leetcode #codinginterview #stlmagic #algorithms
#cpptricks #programming #techreels #cppshorts
#hindicoding #hindiexplanation #codingtricks #cppstl
#fastcode #timecomplexity #cplusplusreels #reelsindia
#techshorts #codeoptimization #coderlife #contentcreation
#jobseekers #100daysofcode #interviewtips #codingchallenge