Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to return the index of first unique character without inbuilt functions using C#?
Finding the index of the first unique character in a string is a common programming problem. The approach involves using a frequency array to count character occurrences, then traversing the string again to find the first character with a count of 1.
The algorithm uses an array of size 256 to accommodate all ASCII characters. First, we count the frequency of each character, then we find the first character that appears exactly once.
Algorithm Steps
The solution follows these steps −
-
Create an integer array of size 256 to store character frequencies
-
Traverse the string and increment the count for each character
-
Traverse the string again and return the index of the first character with frequency 1
-
Return -1 if no unique character is found
Syntax
Following is the basic structure for finding the first unique character −
public int FirstUniqueChar(string s) {
int[] count = new int[256];
// Count frequencies
for (int i = 0; i
Using ASCII Character Mapping
Example
using System;
namespace ConsoleApplication {
public class Arrays {
public int ReturnIndexOfFirstUniqueCharacter(string s) {
int index = -1;
int[] arrayValues = new int[256];
// Count frequency of each character
for (int i = 0; i
The output of the above code is −
String: bookisgreat, First unique index: 0
String: aabbcc, First unique index: -1
String: programming, First unique index: 0
Using Lowercase Character Optimization
For strings containing only lowercase letters, we can optimize by using an array of size 26 −
Example
using System;
namespace ConsoleApplication {
public class StringProcessor {
public int FirstUniqueCharLowercase(string s) {
int[] count = new int[26]; // Only for lowercase a-z
// Count frequencies
for (int i = 0; i Index: " + result +
(result >= 0 ? " ('" + test[result] + "')" : " (No unique character)"));
}
}
}
}
The output of the above code is −
'leetcode' -> Index: 0 ('l')
'loveleetcode' -> Index: 2 ('v')
'aabbcc' -> Index: -1 (No unique character)
'abcdef' -> Index: 0 ('a')
Time and Space Complexity
| Complexity | Value | Explanation |
|---|---|---|
| Time Complexity | O(n) | Two passes through the string of length n |
| Space Complexity | O(1) | Fixed size array (256 or 26 elements) |
Conclusion
Finding the first unique character using a frequency array is an efficient O(n) solution. The approach counts character frequencies in the first pass, then finds the first character with frequency 1 in the second pass, avoiding the need for built-in functions.
