logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›binary search›logic building

Floor and Ceil in Sorted Array

# Question

Given a sorted array nums and an integer x, find the floor and ceiling of x.

  • Floor: The largest element in the array ≤x\le x≤x.
  • Ceiling: The smallest element in the array ≥x\ge x≥x. If no floor or ceiling exists, return -1 for that respective value.

# Solution

# Pattern

Single-Pass Boundary Search Modify a standard Binary Search to search for the first element strictly greater than xxx. Because the array is sorted, this target index naturally gives us the Ceiling, and the index immediately preceding it naturally gives us the Floor.

# How to Identify

  • The array is sorted.
  • You need to find the closest values to a target, bounding it from above and below.
  • Searching for two related boundaries simultaneously often implies they can be found using the exact same binary search state.

# Description

Step-by-step explanation:

  1. Handle edge cases. If the array is empty, return [-1, -1].
  2. Initialize left = 0 and right = nums.length. We set right out of bounds to handle the case where xxx is larger than all elements in the array.
  3. Loop while left < right.
  4. Calculate mid = left + (right - left) / 2.
  5. Optimization: If nums[mid] == x, then xxx exists in the array. By definition, the largest element ≤x\le x≤x is xxx, and the smallest element ≥x\ge x≥x is xxx. Return [x, x] immediately.
  6. Predicate Evaluation: - If nums[mid] > x: The element is strictly greater. It is a candidate for the ceiling. Keep it in the search space and look left: right = mid.
    • If nums[mid] < x: The element is strictly less. It cannot be the ceiling. Discard it and look right: left = mid + 1.
  7. Once the loop ends, left (and right) will point to the index of the first element strictly greater than xxx.
  8. Map to Results:
    • The Ceiling is at index right. (Ensure right < nums.length to avoid out-of-bounds, returning -1 if it is).
    • The Floor is at index right - 1. (Ensure right - 1 >= 0 to avoid out-of-bounds, returning -1 if it is).

# The Intuition

Imagine finding your assigned seat in a sorted theater row. Your ticket says seat 25, but the seats jump from 20 to 30. If you walk down the row, the moment you pass a seat numbered greater than 25 (seat 30), you stop. The seat you are currently looking at (30) is your Ceiling. The seat you just walked past (20) is your Floor. You don't need to walk down the row twice to find both numbers; finding the exact gap between them reveals both boundaries simultaneously. Binary search just helps you find that gap in O(log⁡N)O(\log N)O(logN) time instead of walking linearly.

# Complexity

LabelWorstAverage
Time ComplexityO(log⁡N)O(\log N)O(logN)O(log⁡N)O(\log N)O(logN)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

The search space is halved exactly once per loop iteration. The maximum number of iterations is log⁡2(N)\log_2(N)log2​(N).

# Space Complexity

We use a few primitive pointers and allocate a size-2 array to return the answer. Auxiliary space is strictly O(1)O(1)O(1).

# Code

class Solution {
    public int[] getFloorAndCeil(int[] nums, int x) {
        if (nums == null || nums.length == 0) return new int[]{-1, -1};
 
        int left = 0, right = nums.length;
 
        while (left < right) {
            int mid = left + (right - left) / 2;
            
            if (nums[mid] == x) return new int[]{x, x};
 
            if (nums[mid] > x)  {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
 
        int floor = (right - 1 >= 0) ? nums[right - 1] : -1;
        int ceil = (right < nums.length) ? nums[right] : -1;
 
        return new int[]{floor, ceil}; 
    }
}

# Caveats

  • Two Separate Searches vs One: A naive (but correct) candidate might write two entirely separate binary search functions: one for getFloor and one for getCeil. While asymptotically equivalent O(2log⁡N)→O(log⁡N)O(2 \log N) \rightarrow O(\log N)O(2logN)→O(logN), writing it in a single pass demonstrates superior mastery of binary search state invariants.
  • left &lt;= right Pitfall: If you use the left <= right template with right = mid - 1, the final states of left and right cross each other, making boundary extraction slightly more confusing (left becomes ceil, right becomes floor). The [left, right) template is much cleaner for bounding problems.

# Concepts to Think About

  • Lower/Upper Bound C++ Equivalents: In C++, std::lower_bound returns an iterator to the first element ≥x\ge x≥x (Ceiling). std::upper_bound returns an iterator to the first element &gt; x.
  • Database Indexing: This exact algorithm is how B-Tree database indexes rapidly locate ranges for BETWEEN SQL queries. It finds the floor of the lower bound and the ceiling of the upper bound to fetch the block.
  • The Neighborhood Rule: In sorted arrays, the elements satisfying nums[i]&lt;x and nums[i]≥x are always adjacent. Finding one usually gives you the other for free.
  • Lower Bound as Ceil: Why is lowerBound the same as Ceil? Because both look for the first element that hasn't "failed" the ≥x condition.
  • Edge Cases: What happens when x is smaller than nums[0]? (Ceil is nums[0], Floor is -1). What if x is larger than nums[n-1]? (Ceil is -1, Floor is nums[n-1]).

# Logical Follow-up

Question: What if the array is an infinite data stream (you don't know the length), and you need the floor/ceil of xxx?

Solution: You cannot use nums.length to initialize right. You must first find the search bounds. Initialize left = 0, right = 1. While nums[right] < x, expand the window exponentially: left = right and right = right * 2. Once nums[right] &gt;= x, you have established a finite window [left, right]. You then run the exact same binary search within that window. Total time remains O(log⁡k)O(\log k)O(logk) where kkk is the index of the ceiling.

Question: "Given a sorted array, find the Closest Element to a target xxx. If two numbers are equally close, return the smaller one."

Solution:

  1. Use the Lower Bound logic to find the ceiling.
  2. Compare the absolute difference between xxx and the Ceiling (nums[idx]) and xxx and the Floor (nums[idx-1]).
  3. Return the one with the smaller difference.

Question (Find K Closest Elements): "Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted. If there is a tie, the smaller strategy is preferred."

Solution: A naive L4 solution would be to find the closest element and then expand outwards using two pointers for O(log⁡n+k)O(\log n + k)O(logn+k). However, an L5 candidate might suggest a more elegant Binary Search on the Window.

  1. Intuition: We are looking for the starting index left of a window of size k.
  2. Search Space: The possible starting index left ranges from 0 to n - k.
  3. Binary Search Criteria: We compare the distance of the elements at the edges of the window. For a mid index:
    • Is xxx closer to nums[mid] or nums[mid + k]?
    • If x - nums[mid] &gt; nums[mid + k] - x, then mid is too far to the left, so left = mid + 1.
    • Else, right = mid.
  4. Result: After O(log⁡(n−k))O(\log(n-k))O(log(n−k)) time, we have the start of the perfect window.
PreviousFind First and Last Position of Element in Sorted ArrayNextKth Missing Positive Number
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up