Skip to content

Commit

Permalink
Create 2116. Check if a Parentheses String Can Be Valid (#698)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Jan 27, 2025
2 parents 62c69ab + 9f32bf6 commit 025b6ec
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions 2116. Check if a Parentheses String Can Be Valid
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution {
public:
vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
vector<vector<int>> graph(numCourses);
vector<int> indegree(numCourses);


for(const auto& p : prerequisites) {
graph[p[0]].push_back(p[1]);
indegree[p[1]]++;
}

queue<int> q;
vector<unordered_set<int>> pre(numCourses);

for(int u = 0; u < numCourses; ++u)
if(!indegree[u])
q.push(u);

while(!q.empty()) {
int u = q.front(); q.pop();

for(int v : graph[u]) {
pre[v].insert(u);
pre[v].insert(pre[u].begin(), pre[u].end());

indegree[v]--;
if(!indegree[v])
q.push(v);
}
}


vector<bool> ans(queries.size());
for(int i = 0; i < queries.size(); ++i) {
int u = queries[i][0], v = queries[i][1];
ans[i] = pre[v].find(u) != pre[v].end();
}

return ans;
}
};

0 comments on commit 025b6ec

Please sign in to comment.