You're a product manager analyzing user feedback for your latest software release! ๐
You have a list of features in your product and a collection of user responses from surveys. Each response contains space-separated feature names that users mentioned they liked.
Your goal: Rank features by popularity to prioritize development efforts!
๐ Popularity Rules:
A feature's popularity = number of responses that mention it
If a user mentions the same feature multiple times in one response, count it only once
Sort features in descending order by popularity
If two features have the same popularity, maintain their original order from the features array
Example: If features = ["photoSharing", "videoCall", "chat"] and responses = ["photoSharing videoCall", "videoCall chat chat"], then "videoCall" appears in 2 responses (most popular), while "photoSharing" and "chat" each appear in 1 response. Since "photoSharing" comes before "chat" originally, the result is ["videoCall", "photoSharing", "chat"].
๐ก Note:videoCall appears in 2 responses (most popular). photoSharing and chat each appear in 1 response, but photoSharing comes first in the original order.
๐ก Note:Even though 'like' appears twice and 'share' appears three times in the response, each feature is only counted once per response. All have popularity 1, so original order is preserved.
Constraints
1 โค features.length โค 104
1 โค features[i].length โค 10
features[i] contains only lowercase letters
1 โค responses.length โค 103
1 โค responses[i].length โค 103
responses[i] contains only lowercase letters and spaces
All feature names are unique
Visualization
Tap to expand
Understanding the Visualization
1
Data Collection
Gather all user responses (like collecting feedback cards from restaurant customers)
2
Counting Phase
Build popularity hash map by processing each response and counting unique feature mentions
3
Ranking Phase
Sort features by popularity (descending) and original index (ascending) for tie-breaking
4
Result Generation
Return ranked feature list for product management decisions
Key Takeaway
๐ฏ Key Insight: Separate data collection from decision making - build complete popularity statistics first, then sort efficiently using pre-computed data.
The optimal solution uses a two-pass hash table approach. First pass builds a popularity count map by processing each response once. Second pass sorts features using pre-computed counts. This achieves O(mรk + n log n) time complexity where m=responses, k=avg words per response, n=features.
Common Approaches
Approach
Time
Space
Notes
โ
Two-Pass Hash Table (Optimal)
O(mรk + n log n)
O(u + n)
First pass builds popularity count map, second pass sorts features using the map
Brute Force (Nested Loops)
O(nรmรk)
O(n)
For each feature, count its occurrences across all responses by scanning every response
Two-Pass Hash Table (Optimal) โ Algorithm Steps
Initialize an empty hash map to store feature popularity counts
First pass - Process all responses:
For each response, split into unique words (use set to avoid duplicates)
For each unique word, increment its count in the hash map
Second pass - Sort features:
Create tuples of (feature, popularity, original_index) using the hash map
Sort by popularity (descending) and original index (ascending)
Extract and return the sorted feature names
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Hash Map Creation
Create empty hash map for counting
2
Response Processing
Process each response once, updating counts
3
Count Recording
Hash map now contains all popularity counts
4
Feature Sorting
Use hash map to sort features efficiently
5
Result Generation
Return sorted feature list
Code -
solution.c โ C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORDS 1000
#define MAX_WORD_LEN 100
typedef struct {
char word[MAX_WORD_LEN];
int count;
} WordCount;
typedef struct {
char name[MAX_WORD_LEN];
int popularity;
int index;
} FeatureInfo;
int compareFeatures(const void* a, const void* b) {
FeatureInfo* fa = (FeatureInfo*)a;
FeatureInfo* fb = (FeatureInfo*)b;
if (fa->popularity != fb->popularity) {
return fb->popularity - fa->popularity; // desc by popularity
}
return fa->index - fb->index; // asc by index
}
int findWordIndex(WordCount* words, int size, const char* word) {
for (int i = 0; i < size; i++) {
if (strcmp(words[i].word, word) == 0) {
return i;
}
}
return -1;
}
char** sortFeatures(char** features, int featuresSize, char** responses, int responsesSize, int* returnSize) {
WordCount popularity[MAX_WORDS];
int wordCount = 0;
// First pass: build popularity count map
for (int i = 0; i < responsesSize; i++) {
char temp[1000];
strcpy(temp, responses[i]);
char uniqueWords[MAX_WORDS][MAX_WORD_LEN];
int uniqueCount = 0;
// Extract unique words from current response
char* word = strtok(temp, " ");
while (word != NULL) {
int found = 0;
for (int j = 0; j < uniqueCount; j++) {
if (strcmp(uniqueWords[j], word) == 0) {
found = 1;
break;
}
}
if (!found) {
strcpy(uniqueWords[uniqueCount], word);
uniqueCount++;
}
word = strtok(NULL, " ");
}
// Update popularity counts
for (int j = 0; j < uniqueCount; j++) {
int idx = findWordIndex(popularity, wordCount, uniqueWords[j]);
if (idx == -1) {
strcpy(popularity[wordCount].word, uniqueWords[j]);
popularity[wordCount].count = 1;
wordCount++;
} else {
popularity[idx].count++;
}
}
}
// Second pass: sort features using the count map
FeatureInfo* result = (FeatureInfo*)malloc(featuresSize * sizeof(FeatureInfo));
for (int i = 0; i < featuresSize; i++) {
strcpy(result[i].name, features[i]);
result[i].index = i;
result[i].popularity = 0;
int idx = findWordIndex(popularity, wordCount, features[i]);
if (idx != -1) {
result[i].popularity = popularity[idx].count;
}
}
qsort(result, featuresSize, sizeof(FeatureInfo), compareFeatures);
char** answer = (char**)malloc(featuresSize * sizeof(char*));
for (int i = 0; i < featuresSize; i++) {
answer[i] = (char*)malloc(MAX_WORD_LEN * sizeof(char));
strcpy(answer[i], result[i].name);
}
*returnSize = featuresSize;
free(result);
return answer;
}
int main() {
char* features[] = {"photoSharing", "videoCall", "chat"};
char* responses[] = {"photoSharing videoCall", "videoCall chat chat"};
int returnSize;
char** result = sortFeatures(features, 3, responses, 2, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%s ", result[i]);
free(result[i]);
}
printf("\n");
free(result);
return 0;
}
Time & Space Complexity
Time Complexity
โฑ๏ธ
O(mรk + n log n)
m responses ร k words per response for counting + n log n for sorting features
n
2n
โก Linearithmic
Space Complexity
O(u + n)
u unique words across all responses for hash map + n space for result tuples
n
2n
โก Linearithmic Space
52.0K Views
HighFrequency
~18 minAvg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐กExplanation
AI Ready
๐ก SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom โข Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
๐ก
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
๐ง
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
๐ก
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
๐ฌ
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
๐ง
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
๐ก
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
๐งช
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
๐
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
โก
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
๐ป
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
๐ฌ
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
๐ก
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.