Skip to content

[Feature Request]: Leetcode 263(Easy)-264(Medium) Solution #1100 #1164

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,21 @@ id: letter-combinations-of-a-phone-number
title: Letter Combinations of a Phone Number (LeetCode)
sidebar_label: 0017 Letter Combinations of a Phone Number
tags:
- Back Tracking
- Mapping
- String
- Back Tracking
- Mapping
- String
description: The problem requires generating all letter combinations corresponding to given digits (2-9). The solution utilizes backtracking to explore all combinations efficiently, employing a recursive approach in Java.
sidebar_position: 17
---

## Problem Description

| Problem Statement | Solution Link | LeetCode Profile |
| :------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------- |
| [Letter Combinations of a Phone Number](https://leetcode.com/problems/Letter Combinations of a Phone Number/) | [Letter Combinations of a Phone Number Solution on LeetCode](https://leetcode.com/problems/Letter Combinations of a Phone Number/solutions/5055810/video-two-pointer-solution/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) |
| Problem Statement | Solution Link | LeetCode Profile |
| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- |
| [Letter Combinations of a Phone Number](https://leetcode.com/problems/Letter Combinations of a Phone Number/) | [Letter Combinations of a Phone Number Solution on LeetCode](https://leetcode.com/problems/Letter Combinations of a Phone Number/solutions/5055810/video-two-pointer-solution/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) |

### Problem Description

## Problem Statement:

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

### Examples
Expand All @@ -34,6 +32,7 @@ Given a string containing digits from 2-9 inclusive, return all possible letter
- **Input:** `digits = ""`
- **Output:** `[]`


#### Example 3

- **Input:** `2`
Expand All @@ -48,11 +47,9 @@ Given a string containing digits from 2-9 inclusive, return all possible letter
### Approach

1. **Mapping Digits to Letters:**

- Define a mapping of digits to their corresponding letters, similar to telephone buttons.

2. **Backtracking Function:**

- Define a recursive backtracking function to generate all possible combinations.
- The function takes four parameters:
- `index`: The current index in the digits string.
Expand All @@ -62,7 +59,6 @@ Given a string containing digits from 2-9 inclusive, return all possible letter
- After the recursive call, we remove the last character from the combination (backtracking).

3. **Base Case:**

- If the length of the current combination is equal to the length of the input digits string, we add the combination to the result list.

4. **Main Function:**
Expand Down Expand Up @@ -157,7 +153,6 @@ public class Solution {
```

#### CPP:

```cpp
#include <iostream>
#include <vector>
Expand Down Expand Up @@ -213,82 +208,80 @@ int main() {
```

#### JavaScript

```js
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function (digits) {
if (digits.length === 0) return [];

const digitToLetters = {
2: "abc",
3: "def",
4: "ghi",
5: "jkl",
6: "mno",
7: "pqrs",
8: "tuv",
9: "wxyz",
};

const combinations = [];

const backtrack = (index, path) => {
if (index === digits.length) {
combinations.push(path);
return;
}
const letters = digitToLetters[digits.charAt(index)];
for (let letter of letters) {
backtrack(index + 1, path + letter);
}
};

backtrack(0, "");
return combinations;
var letterCombinations = function(digits) {
if (digits.length === 0) return [];
const digitToLetters = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
};
const combinations = [];
const backtrack = (index, path) => {
if (index === digits.length) {
combinations.push(path);
return;
}
const letters = digitToLetters[digits.charAt(index)];
for (let letter of letters) {
backtrack(index + 1, path + letter);
}
};
backtrack(0, '');
return combinations;
};

// Example usage:
console.log(letterCombinations("23")); // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
```

#### TypeScript

```ts
class Solution {
private digitToLetters: { [key: string]: string } = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
};

letterCombinations(digits: string): string[] {
const combinations: string[] = [];

const backtrack = (index: number, path: string): void => {
if (index === digits.length) {
combinations.push(path);
return;
}
const letters = this.digitToLetters[digits.charAt(index)];
for (let letter of letters) {
backtrack(index + 1, path + letter);
}
private digitToLetters: { [key: string]: string } = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
};

if (digits.length !== 0) {
backtrack(0, "");
}
letterCombinations(digits: string): string[] {
const combinations: string[] = [];

const backtrack = (index: number, path: string): void => {
if (index === digits.length) {
combinations.push(path);
return;
}
const letters = this.digitToLetters[digits.charAt(index)];
for (let letter of letters) {
backtrack(index + 1, path + letter);
}
};

return combinations;
}
if (digits.length !== 0) {
backtrack(0, '');
}

return combinations;
}
}

// Example usage:
Expand All @@ -301,11 +294,9 @@ console.log(solution.letterCombinations("23")); // Output: ["ad","ae","af","bd",
Here's a step-by-step algorithm for generating all possible letter combinations of a given string of digits using backtracking:

1. **Define a mapping of digits to letters:**

- Create a map where each digit from 2 to 9 is mapped to its corresponding letters on a telephone keypad.

2. **Define a backtracking function:**

- The function will take the following parameters:
- `index`: The current index in the digits string.
- `path`: The current combination of letters.
Expand All @@ -314,12 +305,11 @@ Here's a step-by-step algorithm for generating all possible letter combinations
- After the recursive call, remove the last character from the combination (backtracking).

3. **Base Case:**

- If the length of the current combination is equal to the length of the input digits string, add the combination to the result list.

4. **Main Function:**
- Initialize an empty list to store the combinations.
- Call the backtracking function with the initial index set to 0 and an empty string as the initial combination.
- Return the list of combinations.

This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking.
This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking.
122 changes: 122 additions & 0 deletions dsa-solutions/lc-solutions/0200-0299/0263-Ugly-Number.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
---
id: ugly-number
title: Ugly Number
sidebar_label: 0263-Ugly-Number
tags:
- Math
- Number Theory
- C++
- Java
- Python
description: "This document provides a solution to the Ugly Number problem, where we need to determine if a number is an ugly number."
---

## Problem

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer `n`, return `true` if `n` is an ugly number.

### Examples

**Example 1:**

Input: n = 6
Output: true
Explanation: 6 = 2 × 3

**Example 2:**

Input: n = 8
Output: true
Explanation: 8 = 2 × 2 × 2

**Example 3:**

Input: n = 14
Output: false
Explanation: 14 is not an ugly number since it includes the prime factor 7.

**Example 4:**

Input: n = 1
Output: true
Explanation: 1 is typically treated as an ugly number.

### Constraints

- `-2^31 <= n <= 2^31 - 1`

### Approach

To determine if a number is an ugly number, we can follow these steps:

1. If `n` is less than or equal to 0, return `false` since ugly numbers are positive.
2. Divide `n` by 2, 3, and 5 as long as it is divisible by these numbers.
3. After performing the above division, if the resulting number is 1, then `n` is an ugly number. Otherwise, it is not.

### Solution

#### Code in Different Languages

### C++ Solution
```cpp
#include <iostream>

using namespace std;

bool isUgly(int n) {
if (n <= 0) return false;
while (n % 2 == 0) n /= 2;
while (n % 3 == 0) n /= 3;
while (n % 5 == 0) n /= 5;
return n == 1;
}

int main() {
int n = 6;
cout << (isUgly(n) ? "true" : "false") << endl;
}
```
### Java Solution

```java
public class UglyNumber {
public static boolean isUgly(int n) {
if (n <= 0) return false;
while (n % 2 == 0) n /= 2;
while (n % 3 == 0) n /= 3;
while (n % 5 == 0) n /= 5;
return n == 1;
}

public static void main(String[] args) {
int n = 6;
System.out.println(isUgly(n) ? "true" : "false");
}
}
```
### Python Solution

```python
def isUgly(n):
if n <= 0:
return False
for i in [2, 3, 5]:
while n % i == 0:
n //= i
return n == 1

n = 6
print(isUgly(n))
```
### Complexity Analysis
**Time Complexity:** O(logN)
>Reason: The division operations will run in logarithmic time relative to the input value n.

**Space Complexity:** O(1)

>Reason: We use a constant amount of extra space.

This solution checks whether a number is an ugly number by continually dividing the number by 2, 3, and 5. If the result is 1, the number is an ugly number. The time complexity is logarithmic, and the space complexity is constant, making it efficient for large input values.

### References
**LeetCode Problem:** Ugly Number
Loading
Loading