Hacker CS: Computer Science Challenges
hackercs.com
hackercs.com
#include <string.h>
void reverseRange(char *i, char *j) {
char temp;
for (--j; i <= j; ++i, --j) {
temp = *i;
*i = *j;
*j = temp;
}
}
void reverseString(char *str) {
char *ptr;
// reverse the whole string
reverseRange(str, strchr(str,'\0'));
// reverse each individual word
for (ptr = str; *ptr; str = ptr + 1) {
for (ptr = str; *ptr != ' ' && *ptr; ++ptr) {}
reverseRange(str, ptr);
}
}char firstNonRepeatedChar(string s){
HashTable H;
foreach(char c in s) H[c]++;
foreach(char c in s) if(H[c] == 1) return c;
}"abcabcabcabc....abcabcxabcabcabcabc...abcabc"
Assume the string is stored as a linked-list (so removing characters from the middle of the string is cheap). Then remove duplicates from the string during the initial traversal (keep track of unique characters that were removed as duplicates in a hashtable). After this single traversal the character in the head node of the remaining linked-list will be the first non-repeated character in the original string.
Note the string must be stored in the linked-list initially... if we're responsible for moving the string from a theoretical array w/ billions of elements then we have to traverse the string twice just like the original algorithm and nothing is gained.
Please clarify the "usually in the middle" part of your question. In this case do we always have to return the first non-repeated character? Or can we just be close?
The usually in the middle is meant to say that typically the first character returned is position ~s.length/2.
The linked list idea is good. I wasn't thinking of that at all.
import string
def first_nonrepeating_char(s, alphabet=string.printable):
notrepeated = [] # remember order of appearance!
repeated = [] # set of repeated chars, order unimportant
for c in s:
if c in notrepeated:
# c has now been repeated!
notrepeated.remove(c)
repeated.append(c)
if len(repeated) == len(alphabet):
return None # every letter repeated!
elif c not in repeated:
# we have not seen c before
notrepeated.append(c)
return notrepeated[0] if len(notrepeated) > 0 else None
assert first_nonrepeating_char('trait') == 'r'
assert first_nonrepeating_char('aardvark') == 'd'
assert first_nonrepeating_char('aabbac') == 'c'
assert first_nonrepeating_char('aabacc') == 'b'
assert first_nonrepeating_char('aaba ccdbe') == ' '
assert first_nonrepeating_char('aabad ccbe') == 'd'I do like the early exit.
These challenges actually seem to test your knowledge of programming, not mathematical identities.
QQ .. In the very first video on Linked Lists, is the Node type defined correctly? Shouldn't next be a pointer to Node?