{"id":304,"date":"2025-06-13T14:03:40","date_gmt":"2025-06-13T08:33:40","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=304"},"modified":"2025-06-13T14:13:54","modified_gmt":"2025-06-13T08:43:54","slug":"find-second-largest-and-second-smallest-element-in-an-array","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/","title":{"rendered":"Find the second largest and second smallest element in an Array | Explained"},"content":{"rendered":"\n<p>Need the second smallest and second largest in one array? We compare a clear two-pass \u201cbetter\u201d method with a one-pass optimal trick. Full intuition, commented code, dry runs, and Big-O analysis.<\/p>\n\n\n\n<p>So let&#8217;s get started with the [<strong><a href=\"https:\/\/www.naukri.com\/code360\/problems\/ninja-and-the-second-order-elements_6581960\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>].<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-a24376be-0fa1-475d-acfb-9ced7f435168\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#0-1-problem-statement\" style=\"\">1. Problem statement<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#1-2-example\" style=\"\">2. Example<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#2-3-high-level-idea\" style=\"\">3. High-level idea<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#3-4-better-solution-%E2%80%93-two-passes-o-2-pass-\" style=\"\">4. Better solution \u2013 two passes (O 2-pass)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#4-41%E2%80%82intuition\" style=\"\">4.1\u2002Intuition<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#5-42%E2%80%82code\" style=\"\">4.2\u2002Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#6-43%E2%80%82step-by-step-explanation\" style=\"\">4.3\u2002Step-by-step explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#7-44%E2%80%82dry-run-array-5-1-3-4-2-\" style=\"\">4.4\u2002Dry run (array [5, 1, 3, 4, 2])<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#8-45%E2%80%82complexity\" style=\"\">4.5\u2002Complexity<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#9-5-optimal-solution-%E2%80%93-one-pass-o-1-pass-\" style=\"\">5. Optimal solution \u2013 one pass (O 1-pass)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#10-51%E2%80%82why-faster\" style=\"\">5.1\u2002Why faster?<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#11-52%E2%80%82code\" style=\"\">5.2\u2002Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#12-53%E2%80%82step-by-step-explanation\" style=\"\">5.3\u2002Step-by-step explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#13-54%E2%80%82dry-run-on-9-7-\" style=\"\">5.4\u2002Dry run on [9, 7]<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#14-55%E2%80%82complexity\" style=\"\">5.5\u2002Complexity<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#15-6-which-one-to-choose\" style=\"\">6. Which one to choose?<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-second-largest-and-second-smallest-element-in-an-array\/#16-7-key-takeaways\" style=\"\">7. Key takeaways<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-1-problem-statement\">1. Problem statement<\/h2>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>You are given an array <code>a<\/code> of length <code>n<\/code>.<br>Return a list <code>[secondLargest, secondSmallest]<\/code>, where<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>secondLargest<\/code> = the second-largest distinct value in <code>a<\/code><\/li>\n\n\n\n<li><code>secondSmallest<\/code> = the second-smallest distinct value in <code>a<\/code><\/li>\n<\/ul>\n\n\n\n<p>All elements are distinct, and <code>n \u2265 2<\/code>.<\/p>\n<\/blockquote>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-2-example\">2. Example<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th><code>a<\/code><\/th><th>Answer<\/th><th>Why<\/th><\/tr><\/thead><tbody><tr><td><code>[5, 1, 3, 4, 2]<\/code><\/td><td><code>[4, 2]<\/code><\/td><td>Sorted order \u2192 <code>1 &lt; 2 &lt; 3 &lt; 4 &lt; 5<\/code>.<br>Second-largest = 4, second-smallest = 2<\/td><\/tr><tr><td><code>[9, 7]<\/code><\/td><td><code>[7, 9]<\/code><\/td><td>Only two values: second-largest = smaller one (7), second-smallest = larger one (9).<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-3-high-level-idea\">3. High-level idea<\/h2>\n\n\n\n<p>We need the <strong>top two<\/strong> and <strong>bottom two<\/strong> distinct numbers.<br>No sorting is required; a couple of variables can track them while we scan the array.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><em>You may be interested in solving <a href=\"https:\/\/codeanddebug.in\/blog\/check-if-array-is-sorted\/\" data-type=\"post\" data-id=\"310\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><strong>&#8220;Check if array is sorted or not&#8221;<\/strong><\/mark><\/a><\/em>.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-4-better-solution-%E2%80%93-two-passes-o-2-pass-\">4. Better solution \u2013 <em>two passes (O 2-pass)<\/em><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-41%E2%80%82intuition\">4.1\u2002Intuition<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>First pass<\/strong> \u2013 find the <em>absolute<\/em> smallest and largest.<\/li>\n\n\n\n<li><strong>Second pass<\/strong> \u2013 find the best remaining candidates that are\n<ul class=\"wp-block-list\">\n<li>greater than the smallest (\u2192 second-smallest) and<\/li>\n\n\n\n<li>smaller than the largest (\u2192 second-largest).<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-42%E2%80%82code\">4.2\u2002Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"from typing import List\n\n\ndef getSecondOrderElements(n: int, a: List[int]) -&gt; List[int]:\n    small = float(&quot;inf&quot;)\n    second_small = float(&quot;inf&quot;)\n    large = float(&quot;-inf&quot;)\n    second_large = float(&quot;-inf&quot;)\n\n    # -------- Pass 1 : absolute min &amp; max --------\n    for i in range(0, len(a)):\n        small = min(small, a[i])\n        large = max(large, a[i])\n\n    # -------- Pass 2 : second min &amp; second max --------\n    for i in range(0, len(a)):\n        if a[i] &lt; second_small and a[i] != small:      # candidate &gt; min\n            second_small = a[i]\n        if a[i] &gt; second_large and a[i] != large:      # candidate &lt; max\n            second_large = a[i]\n\n    return [second_large, second_small]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> typing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> List<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">getSecondOrderElements<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">n<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">a<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    small = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    second_small = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    large = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    second_large = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #6A9955\"># -------- Pass 1 : absolute min &amp; max --------<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(a)):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        small = <\/span><span style=\"color: #DCDCAA\">min<\/span><span style=\"color: #D4D4D4\">(small, a[i])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        large = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(large, a[i])<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #6A9955\"># -------- Pass 2 : second min &amp; second max --------<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(a)):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> a[i] &lt; second_small <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> a[i] != small:      <\/span><span style=\"color: #6A9955\"># candidate &gt; min<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            second_small = a[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> a[i] &gt; second_large <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> a[i] != large:      <\/span><span style=\"color: #6A9955\"># candidate &lt; max<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            second_large = a[i]<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> [second_large, second_small]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-43%E2%80%82step-by-step-explanation\">4.3\u2002Step-by-step explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>First loop<\/strong> sets <code>small<\/code> and <code>large<\/code>.<\/li>\n\n\n\n<li><strong>Second loop<\/strong> revisits each value:\n<ul class=\"wp-block-list\">\n<li>If it beats the current <code>second_small<\/code> but is <strong>not<\/strong> the absolute min \u2192 update.<\/li>\n\n\n\n<li>If it beats the current <code>second_large<\/code> but is <strong>not<\/strong> the absolute max \u2192 update.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Return the two found numbers.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-44%E2%80%82dry-run-array-5-1-3-4-2-\">4.4\u2002Dry run (array <code>[5, 1, 3, 4, 2]<\/code>)<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Pass<\/th><th>Variables after pass<\/th><\/tr><\/thead><tbody><tr><td>1<\/td><td><code>small=1<\/code>, <code>large=5<\/code><\/td><\/tr><tr><td>2<\/td><td><code>second_small=2<\/code>, <code>second_large=4<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Return <code>[4, 2]<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-45%E2%80%82complexity\">4.5\u2002Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time<\/strong>: <code>O(n)<\/code> + <code>O(n)<\/code> = <code>O(2n)<\/code> \u2192 <strong>O(n)<\/strong> (linear).<\/li>\n\n\n\n<li><strong>Space<\/strong>: <code>O(1)<\/code>.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"9-5-optimal-solution-%E2%80%93-one-pass-o-1-pass-\">5. Optimal solution \u2013 <em>one pass (O 1-pass)<\/em><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-51%E2%80%82why-faster\">5.1\u2002Why faster?<\/h3>\n\n\n\n<p>We can update both first- and second-rank variables <strong>on the same walk<\/strong> with carefully chosen <code>if\u2013elif<\/code> ladders.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-52%E2%80%82code\">5.2\u2002Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"from typing import List\n\n\ndef getSecondOrderElements(n: int, a: List[int]) -&gt; List[int]:\n    small = float(&quot;inf&quot;)\n    second_small = float(&quot;inf&quot;)\n    large = float(&quot;-inf&quot;)\n    second_large = float(&quot;-inf&quot;)\n\n    # -------- Single pass updates everything --------\n    for i in range(0, len(a)):\n        # ----- smaller side -----\n        if a[i] &lt; small:                       # new absolute min\n            second_small = small\n            small = a[i]\n        elif a[i] &lt; second_small and a[i] != small:\n            second_small = a[i]\n\n        # ----- larger side -----\n        if a[i] &gt; large:                       # new absolute max\n            second_large = large\n            large = a[i]\n        elif a[i] &gt; second_large and a[i] != large:\n            second_large = a[i]\n\n    return [second_large, second_small]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> typing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> List<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">getSecondOrderElements<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">n<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">a<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    small = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    second_small = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    large = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    second_large = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #6A9955\"># -------- Single pass updates everything --------<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(a)):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># ----- smaller side -----<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> a[i] &lt; small:                       <\/span><span style=\"color: #6A9955\"># new absolute min<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            second_small = small<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            small = a[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">elif<\/span><span style=\"color: #D4D4D4\"> a[i] &lt; second_small <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> a[i] != small:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            second_small = a[i]<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># ----- larger side -----<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> a[i] &gt; large:                       <\/span><span style=\"color: #6A9955\"># new absolute max<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            second_large = large<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            large = a[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">elif<\/span><span style=\"color: #D4D4D4\"> a[i] &gt; second_large <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> a[i] != large:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            second_large = a[i]<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> [second_large, second_small]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-53%E2%80%82step-by-step-explanation\">5.3\u2002Step-by-step explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Four sentinels<\/strong> start at \u00b1infinity to simplify comparisons.<\/li>\n\n\n\n<li>For each value <code>x<\/code>:\n<ol class=\"wp-block-list\">\n<li><strong>Left block<\/strong> checks the smaller side.\n<ul class=\"wp-block-list\">\n<li>If <code>x<\/code> beats the current smallest, slide the old <code>small<\/code> down to <code>second_small<\/code>, then set <code>small = x<\/code>.<\/li>\n\n\n\n<li>Else if <code>x<\/code> lands strictly between <code>small<\/code> and <code>second_small<\/code>, it becomes the new <code>second_small<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Right block<\/strong> handles the larger side in the same spirit.\n<ul class=\"wp-block-list\">\n<li>If <code>x<\/code> exceeds <code>large<\/code>, push the old <code>large<\/code> down to <code>second_large<\/code>, then set <code>large = x<\/code>.<\/li>\n\n\n\n<li>Else if <code>x<\/code> floats between <code>second_large<\/code> and <code>large<\/code>, it becomes the new <code>second_large<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<\/li>\n<\/ul>\n\n\n\n<p>Because each block is separate, the same element may update both pairs when the array has only two numbers, exactly what we want.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-54%E2%80%82dry-run-on-9-7-\">5.4\u2002Dry run on <code>[9, 7]<\/code><\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th><code>x<\/code><\/th><th>Updates<\/th><\/tr><\/thead><tbody><tr><td>9<\/td><td>Left block \u2192 <code>small=9<\/code>; <code>second_small=inf<\/code>.<br>Right block \u2192 <code>large=9<\/code>; <code>second_large=-inf<\/code>.<\/td><\/tr><tr><td>7<\/td><td>Left block: <code>x &lt; small<\/code> \u2192 <code>second_small=9<\/code>, <code>small=7<\/code>.<br>Right block: <code>x &gt; second_large<\/code> and <code>x != large<\/code> \u2192 <code>second_large=7<\/code>.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Return <code>[7, 9]<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"14-55%E2%80%82complexity\">5.5\u2002Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time<\/strong>: <code>O(n)<\/code> \u2013 single scan.<\/li>\n\n\n\n<li><strong>Space<\/strong>: <code>O(1)<\/code> \u2013 constant variables only.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"15-6-which-one-to-choose\">6. Which one to choose?<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Criterion<\/th><th>Better (2-pass)<\/th><th>Optimal (1-pass)<\/th><\/tr><\/thead><tbody><tr><td>Code clarity<\/td><td>Slightly simpler mental model<\/td><td>Still clear but denser <code>if\u2013elif<\/code> logic<\/td><\/tr><tr><td>Array read count<\/td><td><code>2 \u00d7 n<\/code><\/td><td><code>1 \u00d7 n<\/code><\/td><\/tr><tr><td>Speed difference<\/td><td>Negligible for small <code>n<\/code>; linear either way<\/td><td>Technically half the work<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>For interviews, show the better solution first (clean concept), then improve to the optimal one to demonstrate refinement.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"16-7-key-takeaways\">7. Key takeaways<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Tracking only <strong>two<\/strong> smallest \/ largest values lets you solve \u201csecond-order\u201d problems in constant space.<\/li>\n\n\n\n<li>A clever ordering of <code>if\u2013elif<\/code> statements collapses two passes into one without hurting readability.<\/li>\n\n\n\n<li>Always reset <strong>second<\/strong> variables <strong>before<\/strong> the first ones change, otherwise you lose information.<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/www.codeanddebug.in\/course\/zero-to-hero-python-dsa\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Need the second smallest and second largest in one array? We compare a clear two-pass \u201cbetter\u201d method with a one-pass optimal trick. Full intuition, commented code, dry runs, and Big-O analysis. So let&#8217;s get started with the [Problem Link]. 1. Problem statement 2. Example a Answer Why [5, 1, 3, 4, 2] [4, 2] Sorted<\/p>\n","protected":false},"author":1,"featured_media":306,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4],"tags":[7,8],"class_list":{"0":"post-304","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-beginner","9":"tag-array","10":"tag-easy"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/second-largest-and-smallest-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/304","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=304"}],"version-history":[{"count":4,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/304\/revisions"}],"predecessor-version":[{"id":315,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/304\/revisions\/315"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/306"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=304"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=304"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=304"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}