My solutions to challenges from various online judges, mainly HackerRank.
HackerRank: Super Reduced String
Given a string, repeatedly remove pairs of adjacent matching elements and print the reduced result.
Examples:
abc
➡️ abc
abbc
➡️ ac
abba
➡️ [empty string]
click for part of my solution
int super_reduce(char *a, int n)
{
int cnt=0;
for (int i=0; i!=n; ++i)
{
char ch=a[i];
if (cnt==0 || a[cnt-1]!=ch)//stack empty or top != incoming
a[cnt++] = ch;//push
else
--cnt;//pop
}
return cnt;//length of reduced string
}
Pretty neato and uses nth_element
.
Made an online algorithm that doesn't use extra space, unlike top solutions in search results.
Figured out a pattern to create a linear time solution I haven't seen elsewhere.
Was really satisfying to solve and I think I implemented it well.