Count characters
Here’s your count_characters.md file properly formatted in Markdown with clear structure and consistent code formatting:
# Count Characters, Remove Duplicates, and Sort
## Problem (LeetCode Style)
Given a string `s`, count the occurrence of each character, remove duplicate characters, and return a string of unique characters sorted in ascending order based on their ASCII value.
### Constraints
- `1 <= s.length <= 10^5`
- `s` contains printable ASCII characters.
### Examples
```text
Input: "banana"
Output: "abn"
Input: "programming"
Output: "agimnopr"
Approach¶
- Count each character manually.
- Track characters to avoid duplicates.
- Sort manually without using built-in sort.
TypeScript Code¶
function countAndSortUnique(s: string): string {
let count: { [key: string]: number } = {};
let uniqueChars: string[] = [];
// Count characters and track unique ones
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (!count[c]) {
count[c] = 1;
uniqueChars.push(c);
} else {
count[c]++;
}
}
// Manual sort of unique characters (ascending ASCII order)
for (let i = 0; i < uniqueChars.length - 1; i++) {
for (let j = i + 1; j < uniqueChars.length; j++) {
if (uniqueChars[i] > uniqueChars[j]) {
const temp = uniqueChars[i];
uniqueChars[i] = uniqueChars[j];
uniqueChars[j] = temp;
}
}
}
return uniqueChars.join('');
}
This version uses:
- Proper Markdown headings and subheadings.
- Consistent code block formatting.
- Inline comments in TypeScript for clarity.
- Clear separation of examples and approach.
If you want, I can also make the **sorting approach more efficient** for large strings while keeping it manual, since the current nested loop is `O(n²)`. Do you want me to do that?