{"id":7481,"date":"2025-07-02T15:10:49","date_gmt":"2025-07-02T09:40:49","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7481"},"modified":"2025-07-22T21:43:58","modified_gmt":"2025-07-22T16:13:58","slug":"longest-common-prefix","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/longest-common-prefix\/","title":{"rendered":"Longest Common Prefix"},"content":{"rendered":"\n<!-- Prism.js CSS and JS -->\n<link\n  href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.css\"\n  rel=\"stylesheet\"\n\/>\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\n  .wp_blog_explanation h1,\n  .wp_blog_explanation h2,\n  .wp_blog_explanation h3,\n  .wp_blog_explanation h4,\n  .wp_blog_explanation h5,\n  .wp_blog_explanation h6,\n  .wp_blog_explanation p {\n    margin-top: 10px !important;\n    margin-bottom: 10px !important;\n  }\n<\/style>\n\n\n\n<div class=\"wp_blog_explanation\">\n    <p>\n      This problem focuses on finding the longest common prefix string shared among an array of strings. If no common prefix exists, the result should be an empty string.\n    <\/p>\n  \n    <h2>Steps<\/h2>\n    <ul>\n      <li>Initialize a pointer <code>x<\/code> to track character positions in the first string.<\/li>\n      <li>Iterate through each character of the first string using <code>while<\/code> loop.<\/li>\n      <li>For every character at position <code>x<\/code> in the first string, compare it with the character at the same position in the other strings.<\/li>\n      <li>If a mismatch is found or if the current index exceeds the length of any string, return the substring from the first string from 0 to <code>x<\/code>.<\/li>\n      <li>If the loop completes without any mismatch, return the first string entirely (it is the common prefix).<\/li>\n    <\/ul>\n  \n    <h2>Dry Run<\/h2>\n    <p><strong>Input:<\/strong> <code>[\"flower\", \"flow\", \"flight\"]<\/code><\/p>\n    <ol>\n      <li><code>x = 0<\/code>: Compare &#8216;f&#8217; with all \u2192 match<\/li>\n      <li><code>x = 1<\/code>: Compare &#8216;l&#8217; \u2192 match<\/li>\n      <li><code>x = 2<\/code>: Compare &#8216;o&#8217; vs &#8216;i&#8217; \u2192 mismatch<\/li>\n      <li>Return <code>\"fl\"<\/code><\/li>\n    <\/ol>\n  \n    <h2>Time &#038; Space Complexity<\/h2>\n    <ul>\n      <li><strong>Time Complexity:<\/strong> O(n\u00b7m), where <code>n<\/code> is the number of strings and <code>m<\/code> is the length of the shortest string<\/li>\n      <li><strong>Space Complexity:<\/strong> O(1), as no extra space is used apart from variables<\/li>\n    <\/ul>\n  <\/div>\n  \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=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">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    <!-- JavaScript -->\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\n  var longestCommonPrefix = function(strs) {\n      let x = 0;\n      while (x < strs[0].length) {\n          let ch = strs[0][x];\n          for (let i = 1; i < strs.length; i++) {\n              if (ch != strs[i][x] || x == strs[i].length) {\n                  return strs[0].substring(0, x);\n              }\n          }\n          ++x;\n      }\n      return strs[0];\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <!-- C++ -->\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;vector&gt;\n  using namespace std;\n  \n  string longestCommonPrefix(vector&lt;string&gt;& strs) {\n      int x = 0;\n      while (x < strs[0].length()) {\n          char ch = strs[0][x];\n          for (int i = 1; i < strs.size(); i++) {\n              if (x == strs[i].length() || ch != strs[i][x]) {\n                  return strs[0].substr(0, x);\n              }\n          }\n          ++x;\n      }\n      return strs[0];\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <!-- C -->\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;string.h&gt;\n  \n  char* longestCommonPrefix(char strs[][100], int strsSize) {\n      static char prefix[100];\n      int x = 0;\n      while (1) {\n          char ch = strs[0][x];\n          for (int i = 1; i < strsSize; i++) {\n              if (x >= strlen(strs[i]) || strs[i][x] != ch) {\n                  prefix[x] = '\\0';\n                  return prefix;\n              }\n          }\n          prefix[x] = ch;\n          x++;\n      }\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <!-- Java -->\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\n  public class Solution {\n      public String longestCommonPrefix(String[] strs) {\n          int x = 0;\n          while (x < strs[0].length()) {\n              char ch = strs[0].charAt(x);\n              for (int i = 1; i < strs.length; i++) {\n                  if (x == strs[i].length() || ch != strs[i].charAt(x)) {\n                      return strs[0].substring(0, x);\n                  }\n              }\n              x++;\n          }\n          return strs[0];\n      }\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <!-- Python -->\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\n  def longestCommonPrefix(strs):\n      x = 0\n      while x &lt; len(strs[0]):\n          ch = strs[0][x]\n          for i in range(1, len(strs)):\n              if x == len(strs[i]) or strs[i][x] != ch:\n                  return strs[0][:x]\n          x += 1\n      return strs[0]\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n  \n\n\n\n<a href=\"https:\/\/leetcode.com\/problems\/two-sum\/description\/\" target=\"blank\"\n  >Solve this problem.<\/a\n>\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(\n            \"active\",\n            content.getAttribute(\"data-lang\") === lang\n          );\n        });\n      });\n    });\n  });\n<\/script>\n\n","protected":false},"excerpt":{"rendered":"<p>This problem focuses on finding the longest common prefix string shared among an array of strings. If no common prefix exists, the result should be an empty string. Steps Initialize a pointer x to track character positions in the first string. Iterate through each character of the first string using while loop. For every character<\/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":[322,176,175,174,172,173],"tags":[],"class_list":["post-7481","post","type-post","status-publish","format-standard","category-algorithms-and-data-structures","category-csharp","category-cplusplus","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7481","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=7481"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7481\/revisions"}],"predecessor-version":[{"id":7494,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7481\/revisions\/7494"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7481"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7481"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7481"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}