Second Largest in Array
समस्या
{10, 5, 20, 8, 15} जैसे array में, second largest element 15 है (largest 20 है)। हम इसे बस दो variables इस्तेमाल करके एक pass में ढूँढ सकते हैं — कोई sorting नहीं चाहिए। यह आम interview सवाल है।
दो-variable विचार
first (largest) और second (second largest) रखिए, दोनों सबसे छोटी संभव value से शुरू। हर element को:
- अगर वो
firstको हराए, पुरानाfirstsecondबन जाता है, और यहfirst। - वरना अगर वो
secondको हराए (पर first को नहीं), वोsecondबन जाता है।
Java program
public class SecondLargest {
public static void main(String[] args) {
int[] a = {10, 5, 20, 8, 15};
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int x : a) {
if (x > first) {
second = first; // पुराना max नीचे खिसकता है
first = x;
} else if (x > second && x != first) {
second = x;
}
}
System.out.println("Second largest: " + second);
}
}
दोनों Integer.MIN_VALUE से शुरू होते हैं। हर नया maximum पुराने को second में धकेलता है। दोनों के बीच की values सिर्फ़ second update करती हैं।
Dry run
| x | x > first? | first | second |
|---|---|---|---|
| Start | — | −∞ | −∞ |
| 10 | haan | 10 | −∞ |
| 5 | nahi (5>−∞ second) | 10 | 5 |
| 20 | haan | 20 | 10 |
| 8 | nahi | 20 | 10 |
| 15 | nahi (15>10) | 20 | 15 |
| Second largest = 15 | |||
जब नया सबसे बड़ा आए (20), पुराना सबसे बड़ा (10) second में खिसक जाता है। 15 जैसी values जो second को हराएँ पर first को नहीं, बस second update करती हैं। अंत में second = 15।
एक pass क्यों काफ़ी है
चूँकि हम largest और second largest एक साथ track करते हैं, एक loop हर value एक बार देखता है और जिन दो की हमें परवाह है उन्हें update रखता है। यह O(n) है — बस दूसरा element देखने को पूरा array sort करने (O(n log n)) से तेज़, और यह array नहीं बदलता।
आम गलतियाँ
- Variables को 0 से शुरू करना।
Integer.MIN_VALUEइस्तेमाल कीजिए, वरना negative arrays टूटते हैं। - first को second में खिसकाना भूलना। नए max पर, पुराना max नीचे ले जाइए।
- Duplicate maxes गिनना। distinct second चाहिए तो
x != firstजोड़िए। - अनावश्यक sorting। एक pass तेज़ है और array अछूता रखता है।
सारांश
- Second largest maximum के बाद सबसे बड़ी value है।
- एक pass में
firstऔरsecondtrack कीजिए। - नया maximum पुराने को
secondमें धकेलता है। - सुरक्षा को दोनों
Integer.MIN_VALUEसे शुरू कीजिए। - यह O(n) है — sorting से तेज़ और array नहीं बदलता।
आगे, array sort कीजिए bubble sort से, या दोहराव हटाइए remove duplicates from an array में।
