{"id":489,"date":"2025-07-02T18:30:53","date_gmt":"2025-07-02T13:00:53","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=489"},"modified":"2025-07-02T18:30:54","modified_gmt":"2025-07-02T13:00:54","slug":"implement-lower-bound","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/implement-lower-bound\/","title":{"rendered":"Implement Lower Bound | Floor in a Sorted Array (GFG)"},"content":{"rendered":"\n<p>Given a sorted array&nbsp;<strong>arr[]&nbsp;<\/strong>and an integer&nbsp;<strong>x<\/strong>, find the index (0-based) of the largest element in arr[] that is less than or equal to x. This element is called the&nbsp;<strong>floor<\/strong>&nbsp;of x. If such an element does not exist, return -1.<\/p>\n\n\n\n<p><strong>Note:<\/strong>&nbsp;In case of multiple occurrences of ceil of x, return the index of the last occurrence.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/floor-in-a-sorted-array-1587115620\/1\" 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>] to begin with.<\/p>\n\n\n\n<p><strong>Examples<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input: <\/strong>arr[] = [1, 2, 8, 10, 10, 12, 19], x = 5\n<strong>Output: <\/strong>1<strong>\nExplanation: <\/strong>Largest number less than or equal to 5 is 2, whose index is 1.<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input: <\/strong>arr[] = [1, 2, 8, 10, 10, 12, 19], x = 11\n<strong>Output: <\/strong>4<strong>\nExplanation: <\/strong>Largest Number less than or equal to 11 is 10, whose indices are 3 and 4. The index of last occurrence is 4.<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input: <\/strong>arr[] = [1, 2, 8, 10, 10, 12, 19], x = 0<br><strong>Output: <\/strong>-1<strong>\nExplanation: <\/strong>No element less than or equal to 0 is found. So, output is -1.<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>1 \u2264 arr.size() \u2264 10<sup>6<\/sup><\/li>\n\n\n\n<li>1 \u2264 arr[i] \u2264 10<sup>6<\/sup><\/li>\n\n\n\n<li>0 \u2264 x \u2264<sup>\u00a0<\/sup>arr[n-1]<\/li>\n<\/ul>\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-2fbddef2-ab72-4a4a-8c57-dd62ff5f8944\" 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\/implement-lower-bound\/#0-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-lower-bound\/#1-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-lower-bound\/#2-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-lower-bound\/#3-dry-run-arr-1-2-8-10-11-k-9-\" style=\"\">Dry Run (arr = [1, 2, 8, 10, 11], k = 9)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-lower-bound\/#4-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-lower-bound\/#5-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-intuition-amp-approach\">Intuition &amp; Approach<\/h2>\n\n\n\n<p>Binary search divides the search space in half repeatedly:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Keep a pointer <code>lb<\/code> ( <strong>l<\/strong>ower <strong>b<\/strong>ound) to remember the <strong>best floor index seen so far<\/strong> \u2013 start with <code>-1<\/code> (meaning \u201cno floor yet\u201d).<\/li>\n\n\n\n<li>While <code>low \u2264 high<\/code>\n<ul class=\"wp-block-list\">\n<li>Compute middle <code>mid = (low + high) \/\/ 2<\/code>.<\/li>\n\n\n\n<li><strong>Case 1:<\/strong><code>arr[mid] \u2264 k<\/code>\n<ul class=\"wp-block-list\">\n<li><code>arr[mid]<\/code> is a valid (and possibly better) floor \u2192 <strong>update<\/strong> <code>lb = mid<\/code>.<\/li>\n\n\n\n<li>But there might be an even closer floor to the right, so move <code>low = mid + 1<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Case 2:<\/strong><code>arr[mid] > k<\/code>\n<ul class=\"wp-block-list\">\n<li>Anything at <code>mid<\/code> or right is <strong>too big<\/strong>, so shift left with <code>high = mid \u2013 1<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Loop stops when <code>low<\/code> crosses <code>high<\/code>; <code>lb<\/code> now holds the index of the largest element \u2264 <code>k<\/code>, or <code>-1<\/code> if none exist.<\/li>\n<\/ol>\n\n\n\n<p>This is just a small tweak of classic binary search that <strong>tracks the last \u201cgood\u201d position<\/strong> seen.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-code-implementation\">Code Implementation<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" 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;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);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=\"class Solution:\n    def findFloor(self, arr, k):\n        n = len(arr)\n        lb = -1               # floor index; -1 means no floor yet\n        low, high = 0, n - 1  # binary-search boundaries\n\n        while low &lt;= high:\n            mid = (low + high) \/\/ 2        # middle index\n\n            if arr[mid] &lt;= k:\n                lb = mid                   # potential (better) floor\n                low = mid + 1              # look on the right side\n            else:\n                high = mid - 1             # look on the left side\n\n        return lb                           # final floor index (or -1)\" 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: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">findFloor<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">k<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(arr)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        lb = -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">               <\/span><span style=\"color: #6A9955\"># floor index; -1 means no floor yet<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        low, high = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, n - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># binary-search boundaries<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> low &lt;= high:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            mid = (low + high) \/\/ <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># middle index<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> arr[mid] &lt;= k:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                lb = mid                   <\/span><span style=\"color: #6A9955\"># potential (better) floor<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                low = mid + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">              <\/span><span style=\"color: #6A9955\"># look on the right side<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                high = mid - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">             <\/span><span style=\"color: #6A9955\"># look on the left side<\/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\"> lb                           <\/span><span style=\"color: #6A9955\"># final floor index (or -1)<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-code-explanation\">Code Explanation<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>lb<\/code> (lower bound)<\/strong> keeps the best floor found so far.<\/li>\n\n\n\n<li><strong>Binary search window<\/strong> <code>[low \u2026 high]<\/code> always contains candidates we haven\u2019t ruled out.<\/li>\n\n\n\n<li>When <code>arr[mid]<\/code> is <strong>\u2264 <code>k<\/code><\/strong>, it\u2019s a valid floor, so store its index and push <code>low<\/code> right to hunt for an even closer floor.<\/li>\n\n\n\n<li>When <code>arr[mid]<\/code> is <strong>> <code>k<\/code><\/strong>, everything right of <code>mid<\/code> is larger than <code>k<\/code>; discard that half by moving <code>high<\/code> left.<\/li>\n\n\n\n<li>The loop ends when no unexamined indices remain. The answer is whatever index <code>lb<\/code> holds (or <code>-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=\"3-dry-run-arr-1-2-8-10-11-k-9-\">Dry Run (arr = <code>[1, 2, 8, 10, 11]<\/code>, k = <code>9<\/code>)<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Step<\/th><th><code>low<\/code><\/th><th><code>high<\/code><\/th><th><code>mid<\/code><\/th><th><code>arr[mid]<\/code><\/th><th><code>lb<\/code> (floor idx)<\/th><th>Action<\/th><\/tr><\/thead><tbody><tr><td>1<\/td><td>0<\/td><td>4<\/td><td>2<\/td><td>8<\/td><td>2<\/td><td>8 \u2264 9 \u2192 <code>lb = 2<\/code>, <code>low = 3<\/code><\/td><\/tr><tr><td>2<\/td><td>3<\/td><td>4<\/td><td>3<\/td><td>10<\/td><td>2<\/td><td>10 &gt; 9 \u2192 <code>high = 2<\/code><\/td><\/tr><tr><td>End<\/td><td>\u2014<\/td><td>\u2014<\/td><td>\u2014<\/td><td>\u2014<\/td><td>2<\/td><td>loop stops (<code>low &gt; high<\/code>)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Output index <code>2<\/code> (value <code>8<\/code>), which is the largest number \u2264 <code>9<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-time-amp-space-complexity\">Time &amp; Space Complexity<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Metric<\/th><th>Precise<\/th><th>Simplified<\/th><\/tr><\/thead><tbody><tr><td><strong>Time<\/strong><\/td><td><code>O(log\u2082 n)<\/code> comparisons<\/td><td><code>O(log n)<\/code><\/td><\/tr><tr><td><strong>Space<\/strong><\/td><td><code>O(1)<\/code> auxiliary<\/td><td>Constant<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Binary search guarantees logarithmic time, and only a couple of integer variables are used, so space stays constant.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-conclusion\">Conclusion<\/h2>\n\n\n\n<p>Finding the <strong>floor in a sorted array<\/strong> is a classic example of how small tweaks to binary search can solve seemingly new problems:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Track<\/strong> the best candidate while you divide the search space.<\/li>\n\n\n\n<li><strong>Update<\/strong> the candidate whenever you find a closer match.<\/li>\n<\/ul>\n\n\n\n<p>Master this pattern and you\u2019ll be equipped for a wide range of \u201cclosest element\u201d questions on sorted data. Happy searching!<\/p>\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:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">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\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given a sorted array&nbsp;arr[]&nbsp;and an integer&nbsp;x, find the index (0-based) of the largest element in arr[] that is less than or equal to x. This element is called the&nbsp;floor&nbsp;of x. If such an element does not exist, return -1. Note:&nbsp;In case of multiple occurrences of ceil of x, return the index of the last occurrence.<\/p>\n","protected":false},"author":1,"featured_media":490,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ub_ctt_via":"","footnotes":""},"categories":[3,4],"tags":[7,27],"class_list":{"0":"post-489","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-binary-search"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/07\/lower-bound-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\/489","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=489"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/489\/revisions"}],"predecessor-version":[{"id":494,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/489\/revisions\/494"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/490"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=489"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=489"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=489"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}