{"id":6237,"date":"2025-05-30T19:59:37","date_gmt":"2025-05-30T14:29:37","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6237"},"modified":"2025-05-30T19:59:37","modified_gmt":"2025-05-30T14:29:37","slug":"find-the-second-largest-number-in-an-array","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/find-the-second-largest-number-in-an-array\/","title":{"rendered":"Find the Second Largest Number in an Array"},"content":{"rendered":"\n<!-- Prism.js CSS and JS -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.css\" rel=\"stylesheet\" \/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n  .wp_blog_code-tabs-container {\n    font-family: \"Segoe UI\", sans-serif !important;\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    border: 1px solid #ddd !important;\n    border-radius: 8px !important;\n    overflow: hidden !important;\n    background-color: white !important;\n  }\n\n  .wp_blog_code-tabs-header {\n    background: #f7f7f7 !important;\n    display: flex !important;\n    border-bottom: 1px solid #ddd !important;\n  }\n\n  .wp_blog_code-tab-button {\n    flex: 1 !important;\n    padding: 10px 15px !important;\n    border: none !important;\n    background: transparent !important;\n    cursor: pointer !important;\n    font-weight: bold !important;\n    transition: background 0.2s !important;\n    color: #242B33 !important;\n  }\n\n  .wp_blog_code-tab-button.active {\n    background: white !important;\n    border-bottom: 3px solid #0073aa !important;\n  }\n\n  .wp_blog_code-tab-content {\n    display: none !important;\n    padding: 20px !important;\n    background: #242B33 !important;\n  }\n\n  .wp_blog_code-tab-content > pre {\n    background: #242B33 !important;\n  }\n\n  .wp_blog_code-tab-content.active {\n    display: block !important;\n  }\n\n  .wp_blog_code-tab-content pre {\n    margin: 0 !important;\n    overflow-x: auto !important;\n  }\n\n  .wp_blog_explanation {\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    font-family: \"Segoe UI\", sans-serif !important;\n    line-height: 1.6 !important;\n    background: white !important;\n    color: black !important;\n    padding: 1rem !important;\n    border-radius: 8px !important;\n  }\n\n  .wp_blog_explanation h2 {\n    color: #0073aa !important;\n    font-size: 1.5rem !important;\n    margin-bottom: 0.5rem !important;\n  }\n\n  .wp_blog_explanation code {\n    background: #f1f1f1 !important;\n    padding: 2px 6px !important;\n    border-radius: 4px !important;\n    font-family: monospace !important;\n  }\n<\/style>\n\n<!-- Explanation Block -->\n<div class=\"wp_blog_explanation\">\n  <h2>Question: Find the Second Largest Number in an Array<\/h2>\n  <p>Write a function <code>secondLargest(arr)<\/code> that takes an array of numbers and returns the second largest unique number in the array.<\/p>\n\n  <h2>Requirements<\/h2>\n  <ul>\n    <li>The array must contain at least two numbers.<\/li>\n    <li>If the array contains all equal elements or only one unique element, return: <code>\"No second largest found\"<\/code><\/li>\n    <li>If the array has less than two elements, return: <code>\"Array should have at least two numbers\"<\/code><\/li>\n  <\/ul>\n\n  <h2>Constraints<\/h2>\n  <ul>\n    <li>Time Complexity: <code>O(n)<\/code> (Single pass through the array)<\/li>\n    <li>Space Complexity: <code>O(1)<\/code><\/li>\n  <\/ul>\n\n  <h2>Examples<\/h2>\n  <pre><code>Input: [0, 3, 5, 2, 7, 9]\nOutput: 7\n\nInput: [4, 4, 4, 4]\nOutput: \"No second largest found\"\n\nInput: [5]\nOutput: \"Array should have at least two numbers\"\n\nInput: [10, 20]\nOutput: 10<\/code><\/pre>\n\n  <h2>Approach<\/h2>\n  <ul>\n    <li>Check array length. If fewer than 2 elements, return appropriate message.<\/li>\n    <li>Initialize <code>firstLargest<\/code> and <code>secondLargest<\/code> to smallest possible values.<\/li>\n    <li>Iterate through array and update values accordingly:<\/li>\n    <ul>\n      <li>If current number &gt; <code>firstLargest<\/code>: update <code>secondLargest<\/code> then <code>firstLargest<\/code>.<\/li>\n      <li>Else if current number &gt; <code>secondLargest<\/code> and != <code>firstLargest<\/code>: update <code>secondLargest<\/code>.<\/li>\n    <\/ul>\n    <li>After loop, check if <code>secondLargest<\/code> was updated. If not, return message.<\/li>\n  <\/ul>\n\n  <h2>Time &#038; Space Complexity<\/h2>\n  <ul>\n    <li>Time Complexity: <code>O(n)<\/code> &#8211; Single pass through the array.<\/li>\n    <li>Space Complexity: <code>O(1)<\/code> &#8211; Constant space used for two variables.<\/li>\n  <\/ul>\n<\/div>\n\n<!-- Code Tabs -->\n<div class=\"wp_blog_code-tabs-container\">\n  <div class=\"wp_blog_code-tabs-header\">\n    <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n    <pre><code class=\"language-javascript\">\nfunction secondLargest(arr) {\n  if (arr.length < 2) return \"Array should have at least two numbers\";\n  let first = -Infinity, second = -Infinity;\n  for (let i = 0; i < arr.length; i++) {\n    if (arr[i] > first) {\n      second = first;\n      first = arr[i];\n    } else if (arr[i] > second && arr[i] !== first) {\n      second = arr[i];\n    }\n  }\n  return second === -Infinity ? \"No second largest found\" : second;\n}\n\nconsole.log(secondLargest([0, 3, 5, 2, 7, 9])); \/\/ 7\n    <\/code><\/pre>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n    <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;limits.h&gt;\n\nconst char* secondLargest(int arr[], int n, int* second) {\n  if (n < 2) return \"Array should have at least two numbers\";\n  int first = INT_MIN;\n  *second = INT_MIN;\n  for (int i = 0; i < n; i++) {\n    if (arr[i] > first) {\n      *second = first;\n      first = arr[i];\n    } else if (arr[i] > *second && arr[i] != first) {\n      *second = arr[i];\n    }\n  }\n  return (*second == INT_MIN) ? \"No second largest found\" : NULL;\n}\n\nint main() {\n  int arr[] = {0, 3, 5, 2, 7, 9};\n  int second;\n  const char* msg = secondLargest(arr, 6, &second);\n  if (msg) printf(\"%s\\n\", msg);\n  else printf(\"%d\\n\", second);\n  return 0;\n}\n    <\/code><\/pre>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n    <pre><code class=\"language-cpp\">\n#include &lt;iostream&gt;\n#include &lt;climits&gt;\nusing namespace std;\n\nstring secondLargest(int arr[], int n) {\n  if (n < 2) return \"Array should have at least two numbers\";\n  int first = INT_MIN, second = INT_MIN;\n  for (int i = 0; i < n; i++) {\n    if (arr[i] > first) {\n      second = first;\n      first = arr[i];\n    } else if (arr[i] > second && arr[i] != first) {\n      second = arr[i];\n    }\n  }\n  return (second == INT_MIN) ? \"No second largest found\" : to_string(second);\n}\n\nint main() {\n  int arr[] = {0, 3, 5, 2, 7, 9};\n  cout << secondLargest(arr, 6) << endl;\n  return 0;\n}\n    <\/code><\/pre>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n    <pre><code class=\"language-java\">\npublic class Main {\n  public static String secondLargest(int[] arr) {\n    if (arr.length < 2) return \"Array should have at least two numbers\";\n    int first = Integer.MIN_VALUE;\n    int second = Integer.MIN_VALUE;\n    for (int num : arr) {\n      if (num > first) {\n        second = first;\n        first = num;\n      } else if (num > second && num != first) {\n        second = num;\n      }\n    }\n    return (second == Integer.MIN_VALUE) ? \"No second largest found\" : String.valueOf(second);\n  }\n\n  public static void main(String[] args) {\n    int[] arr = {0, 3, 5, 2, 7, 9};\n    System.out.println(secondLargest(arr));\n  }\n}\n    <\/code><\/pre>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n    <pre><code class=\"language-python\">\ndef second_largest(arr):\n    if len(arr) < 2:\n        return \"Array should have at least two numbers\"\n    first = float('-inf')\n    second = float('-inf')\n    for num in arr:\n        if num > first:\n            second = first\n            first = num\n        elif num > second and num != first:\n            second = num\n    return second if second != float('-inf') else \"No second largest found\"\n\nprint(second_largest([0, 3, 5, 2, 7, 9]))  # 7\n    <\/code><\/pre>\n  <\/div>\n<\/div>\n\n<!-- Tab Switch Script -->\n<script>\n  document.addEventListener('DOMContentLoaded', function () {\n    const buttons = document.querySelectorAll('.wp_blog_code-tab-button');\n    const contents = document.querySelectorAll('.wp_blog_code-tab-content');\n\n    buttons.forEach(button => {\n      button.addEventListener('click', () => {\n        const lang = button.getAttribute('data-lang');\n\n        buttons.forEach(btn => btn.classList.remove('active'));\n        button.classList.add('active');\n\n        contents.forEach(content => {\n          content.classList.toggle('active', content.getAttribute('data-lang') === lang);\n        });\n      });\n    });\n  });\n<\/script>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Question: Find the Second Largest Number in an Array Write a function secondLargest(arr) that takes an array of numbers and returns the second largest unique number in the array. Requirements The array must contain at least two numbers. If the array contains all equal elements or only one unique element, return: &#8220;No second largest found&#8221;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[260,811,810,174,172,173],"tags":[],"class_list":{"0":"post-6237","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-c-c-plus-plus","7":"category-data-structures-and-algorithms","8":"category-dsa","9":"category-java","10":"category-javascript","11":"category-python"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6237","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6237"}],"version-history":[{"count":2,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6237\/revisions"}],"predecessor-version":[{"id":6249,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6237\/revisions\/6249"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6237"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6237"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6237"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}