forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leftmost_nonrepeating_char.c
48 lines (43 loc) · 994 Bytes
/
leftmost_nonrepeating_char.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdio.h>
#include <stdlib.h>
struct pair
{
int first;
int second;
};
int find_char_index(char *str)
{
struct pair p[256] = {0};
for (int i = 0; str[i]; i++)
{
(p[str[i]].first)++;
p[str[i]].second = i;
}
int index = 10001;
for (int i = 0; i < 256; i++)
{
if (p[i].first == 1)
index = index > p[i].second ? p[i].second : index;
}
return index;
}
int main()
{
char str[10000];
printf("Enter a string: ");
scanf("%s", str);
int index = find_char_index(str);
if (index == 10001)
printf("%d", -1);
else
printf("%d", index);
return 0;
}
/*
Given a string, find the index of the leftmost non repeating character in it.
Example: s = "hello", output should be: 0 (index of h)
s = "aabcdb", output should be: 3 (index of c)
s = "xxyyzz", output should be -1 (since there is no non repeating character in this string)
Time Complexity: O(n)
Space Complexity: O(n)
*/