
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 26
void alienOrder(char* words[], int n, int k) {
int adj[MAX][MAX] = {0};
int indegree[MAX] = {0};
for (int i = 0; i < n - 1; i++) {
char* w1 = words[i];
char* w2 = words[i + 1];
int len = strlen(w1) < strlen(w2) ? strlen(w1) : strlen(w2);
for (int j = 0; j < len; j++) {
if (w1[j] != w2[j]) {
int u = w1[j] - 'a';
int v = w2[j] - 'a';
if (!adj[u][v]) {
adj[u][v] = 1;
indegree[v]++;
}
break;
}
}
}
char queue[MAX];
int front = 0, rear = 0;
for (int i = 0; i < k; i++) {
if (indegree[i] == 0) queue[rear++] = i;
}
while (front < rear) {
int u = queue[front++];
printf("%c", u + 'a');
for (int v = 0; v < k; v++) {
if (adj[u][v]) {
if (--indegree[v] == 0) queue[rear++] = v;
}
}
}
printf("\n");
}
int main() {
char* words[] = {"caa", "aaa", "aab"};
int n = 3;
int k = 3;
printf("Order: ");
alienOrder(words, n, k);
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(N + K) | We must iterate through all N characters to build the graph and process up to K nodes during topological sort. No skipping possible. |
| Average Case | O(N + K) | Building edges between characters takes O(N) time and topological sorting over K nodes also takes O(K). |
| Worst Case | O(N + K) | Even if all characters are interconnected, we must build the graph using all N words and sort up to K characters. |