Python Second Largest Element in Array

🔍 Finding Second Largest Element in Python Practiced a common interview problem: 👉 Find the second largest element in an array ✅ Approach 1: Two Loops First loop → find maximum Second loop → find second maximum ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🚀 Approach 2: Optimized Single Loop Maintain two variables (first, second) Update both in one traversal ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🎯 Key Insight: Both approaches are linear, but the single-loop solution is cleaner and more efficient in practice since it avoids traversing the array twice. Improving logic step-by-step helps build strong problem-solving fundamentals 🚀 def sec_larg(arr):   max = 0   for i in range(0,len(arr)):     if arr[i]>max:       max = arr[i]    sec_max = 0   for i in range(0,len(arr)):     if(arr[i]>sec_max and arr[i]!=max):       sec_max = arr[i]   return sec_max arr = [3,2,1,8,] res = sec_larg(arr) print(res) #Python #DSA #CodingInterview #ProblemSolving 10000 CodersManoj Kumar Reddy ParlapalliManivardhan Jakka

To view or add a comment, sign in

Explore content categories