Date: September 25, 2024.
Hello Everyone,
Today marks Day 30 of my competitive programming journey, and I'm excited to share what I've learned.
What I Did Today:
I tackled two problems: Spiral Traversal of a Matrix and Check if Two Strings are Anagrams of Each Other.
1. Spiral Traversal of a Matrix:
Problem:
Given a 2D matrix, traverse it in a spiral order.
Explanation:
To solve this problem, I used boundary pointers (top, bottom, left, right) to control the traversal of the matrix. The traversal is done in a spiral order, starting from the top-left corner and moving right, down, left, and then up, while progressively shrinking the boundaries as each row or column is processed. This approach ensures that all elements are visited without overlapping or missing any.
Here's the implementation:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.empty()) return result;
int top = 0, bottom = matrix.size() - 1;
int left = 0, right = matrix[0].size() - 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
result.push_back(matrix[top][i]);
}
top++;
for (int i = top; i <= bottom; i++) {
result.push_back(matrix[i][right]);
}
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) {
result.push_back(matrix[bottom][i]);
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
result.push_back(matrix[i][left]);
}
left++;
}
}
return result;
}
2. Check if Two Strings are Anagrams of Each Other:
Problem:
Given two strings, check if they are anagrams (contain the same characters in the same frequency).
Explanation:
The solution involves counting the frequency of each character in both strings and comparing the counts.
Here's the implementation:
bool areAnagrams(string str1, string str2) {
if (str1.length() != str2.length()) return false;
vector<int> count(26, 0);
for (char c : str1) {
count[c - 'a']++;
}
for (char c : str2) {
count[c - 'a']--;
}
for (int freq : count) {
if (freq != 0) return false;
}
return true;
}
Reflection:
Today's problems were fun and insightful. The spiral traversal of a matrix was a bit tricky, but breaking it into smaller steps helped a lot. Checking for anagrams was simpler but reinforced the importance of character frequency in strings.
Stay tuned for more updates, and feel free to share your thoughts and experiences!
Top comments (0)