{"id":493,"date":"2025-07-02T18:36:04","date_gmt":"2025-07-02T13:06:04","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=493"},"modified":"2025-07-02T18:36:50","modified_gmt":"2025-07-02T13:06:50","slug":"implement-upper-bound","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/implement-upper-bound\/","title":{"rendered":"Implement Upper Bound"},"content":{"rendered":"\n<p>In a <strong>sorted<\/strong> array <code>arr[]<\/code>, the <strong>upper bound of <code>x<\/code><\/strong> is the index of the <strong>first element that is strictly greater than <code>x<\/code><\/strong>.<br>If every element in the array is \u2264 <code>x<\/code>, the conventional upper-bound position is <code>n<\/code> (one past the last index).<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.naukri.com\/code360\/problems\/implement-upper-bound_8165383?leftPanelTabValue=PROBLEM\" 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<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>Example<\/strong><br><code>arr = [1, 2, 4, 4, 6], x = 4<\/code><br><em>Upper bound<\/em> \u2192 index <code>4<\/code> (value <code>6<\/code>), because indices <code>0\u20133<\/code> are \u2264 <code>4<\/code> and index <code>4<\/code> is the first <code>&gt; 4<\/code>.<\/p>\n<\/blockquote>\n\n\n\n<p>Upper-bound queries power range searches, frequency counts, and insertion-point calculations. A tailored binary-search achieves this in logarithmic time.<\/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-300730c9-eb39-44e0-823c-710d8d1fe97a\" 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-upper-bound\/#0-optimal-solution-binary-search\" style=\"\">Optimal Solution (Binary Search)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-upper-bound\/#1-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-upper-bound\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-upper-bound\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-upper-bound\/#4-dry-run-arr-1-2-4-4-6-x-4-\" style=\"\">Dry Run (arr = [1, 2, 4, 4, 6], x = 4)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-upper-bound\/#5-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/implement-upper-bound\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-optimal-solution-binary-search\">Optimal Solution (Binary Search)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-amp-approach\">Intuition &amp; Approach<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Search Window<\/strong> \u2013 Maintain two pointers, <code>low<\/code> and <code>high<\/code>, around the current candidate range.<\/li>\n\n\n\n<li><strong>Potential Answer Tracker<\/strong> \u2013 Keep <code>ub<\/code>, the best upper-bound index seen so far, initialised to <code>n<\/code> (meaning \u201cnot found yet\u201d).<\/li>\n\n\n\n<li><strong>Binary Search Loop<\/strong>\n<ul class=\"wp-block-list\">\n<li>Compute <code>mid<\/code>.<\/li>\n\n\n\n<li>If <code>arr[mid] > x<\/code>, <code>mid<\/code> is a valid upper bound. Save it in <code>ub<\/code> and continue searching <strong>left<\/strong> (smaller indices) for an even earlier position.<\/li>\n\n\n\n<li>Otherwise (<code>arr[mid] \u2264 x<\/code>) move <code>low<\/code> right to discard non-qualifying elements.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>When the loop terminates, <code>ub<\/code> holds either the first index of an element > <code>x<\/code> or <code>n<\/code> if such an element doesn\u2019t exist.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/h3>\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=\"def upperBound(arr: [int], x: int, n: int) -&gt; int:\n    n = len(arr)                 # total number of elements\n    ub = n                       # default upper bound (past-the-end)\n    low, high = 0, n - 1         # binary-search boundaries\n\n    while low &lt;= high:\n        mid = (low + high) \/\/ 2  # midpoint of current window\n\n        if arr[mid] &gt; x:\n            ub = mid             # arr[mid] is a better (earlier) upper bound\n            high = mid - 1       # search the left half for an even smaller index\n        else:                    # arr[mid] &lt;= x \u2192 discard left half including mid\n            low = mid + 1        # shift window right to find a greater element\n\n    return ub                    # final upper-bound index (or n if none)\" 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\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">upperBound<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">: [<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #9CDCFE\">x<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/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\">) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/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 style=\"color: #6A9955\"># total number of elements<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    ub = n                       <\/span><span style=\"color: #6A9955\"># default upper bound (past-the-end)<\/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\"># midpoint of current window<\/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] &gt; x:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            ub = mid             <\/span><span style=\"color: #6A9955\"># arr[mid] is a better (earlier) upper bound<\/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\"># search the left half for an even smaller index<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:                    <\/span><span style=\"color: #6A9955\"># arr[mid] &lt;= x \u2192 discard left half including mid<\/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\"># shift window right to find a greater element<\/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\"> ub                    <\/span><span style=\"color: #6A9955\"># final upper-bound index (or n if none)<\/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<h3 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>ub<\/code> = <code>n<\/code><\/strong> acts as a sentinel meaning \u201cno upper bound found yet.\u201d<\/li>\n\n\n\n<li><strong>Case <code>arr[mid] > x<\/code><\/strong>\n<ul class=\"wp-block-list\">\n<li><code>mid<\/code> itself qualifies. Store it and shrink the window <strong>leftward<\/strong> to see if an earlier qualifying index exists.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Case <code>arr[mid] &lt;= x<\/code><\/strong>\n<ul class=\"wp-block-list\">\n<li>All indices \u2264 <code>mid<\/code> are \u2264 <code>x<\/code>, so the next valid upper bound must be to the <strong>right<\/strong>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Loop ends when <code>low<\/code> crosses <code>high<\/code>; at that point every potential position is checked and <code>ub<\/code> is final.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-dry-run-arr-1-2-4-4-6-x-4-\">Dry Run (arr = <code>[1, 2, 4, 4, 6]<\/code>, x = <code>4<\/code>)<\/h3>\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>ub<\/code> update<\/th><th>Next Window<\/th><\/tr><\/thead><tbody><tr><td>1<\/td><td>0<\/td><td>4<\/td><td>2<\/td><td>4<\/td><td>\u2014 (still 5)<\/td><td><code>low = 3<\/code><\/td><\/tr><tr><td>2<\/td><td>3<\/td><td>4<\/td><td>3<\/td><td>4<\/td><td>\u2014 (still 5)<\/td><td><code>low = 4<\/code><\/td><\/tr><tr><td>3<\/td><td>4<\/td><td>4<\/td><td>4<\/td><td>6<\/td><td><code>ub = 4<\/code><\/td><td><code>high = 3<\/code><\/td><\/tr><tr><td>End<\/td><td>\u2014<\/td><td>\u2014<\/td><td>\u2014<\/td><td>\u2014<\/td><td><strong>ub = 4<\/strong><\/td><td>loop stops<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Result <strong>4<\/strong>, matching the expected upper-bound index.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-time-amp-space-complexity\">Time &amp; Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> <code>O(log n)<\/code> \u2014 each iteration halves the search space.<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(1)<\/code> \u2014 only a few integer variables are used.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h3>\n\n\n\n<p>By slightly tweaking classic binary search, tracking the last \u201cgood\u201d index, we can compute the <strong>upper bound<\/strong> in logarithmic time and constant space. This pattern generalises to numerous \u201cfirst\/last element with property P\u201d queries on sorted data. Happy coding!<\/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\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In a sorted array arr[], the upper bound of x is the index of the first element that is strictly greater than x.If every element in the array is \u2264 x, the conventional upper-bound position is n (one past the last index). Here&#8217;s the [Problem Link] to begin with. Examplearr = [1, 2, 4, 4,<\/p>\n","protected":false},"author":1,"featured_media":495,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4],"tags":[7,27],"class_list":{"0":"post-493","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\/upper-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\/493","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=493"}],"version-history":[{"count":3,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/493\/revisions"}],"predecessor-version":[{"id":499,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/493\/revisions\/499"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/495"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=493"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=493"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=493"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}