386. Lexicographical Numbers #583
              
                
                  
                  
                    Answered
                  
                  by
                    basharul-siddike
                  
              
          
                  
                    
                      mah-shamim
                    
                  
                
                  asked this question in
                Q&A
              
            -
| Topics:  Given an integer  You must write an algorithm that runs in  Example 1: 
 Example 2: 
 Constraints: 
 | 
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            basharul-siddike
          
      
      
        Sep 21, 2024 
      
    
    Replies: 1 comment 2 replies
-
| We can approach it using a Depth-First Search (DFS)-like strategy. Key Insights:
 Approach:
 Let's implement this solution in PHP: 386. Lexicographical Numbers <?php
/**
 * @param Integer $n
 * @return Integer[]
 */
function lexicalOrder($n) {
    $result = [];
    $current = 1;
    
    // Loop to collect all numbers in lexicographical order
    for ($i = 0; $i < $n; $i++) {
        $result[] = (int)$current;
        
        // Try to go deeper in the tree by multiplying by 10
        if ($current * 10 <= $n) {
            $current *= 10;
        } else {
            // If we can't go deeper, try to increment the current number
            if ($current >= $n) {
                $current /= 10;
            }
            $current++;
            while ($current % 10 == 0) {
                $current /= 10;
            }
        }
    }
    
    return $result;
}
// Example usage
$n1 = 13;
print_r(lexicalOrder($n1));
$n2 = 2;
print_r(lexicalOrder($n2));
?>Explanation:
 Example Walkthrough:Input:  | 
Beta Was this translation helpful? Give feedback.
                  
                    2 replies
                  
                
            
      Answer selected by
        mah-shamim
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
We can approach it using a Depth-First Search (DFS)-like strategy.
Key Insights:
1, and each node has up to 9 children, which are formed by appending digits (0 to 9).1and repeatedly appending numbers, ensuring we don't exceed the givenn.Approach:
1and attempt to go deeper by multiplying by10(i.e., the next lexicographical number with the next digit).n), increment the number, ensuring that it doesn’t introduce an invalid…