๐งฑ Arrays in C# โ A Practical Guide for Interview Preparation
Arrays are one of the most fundamental data structures used in programming and appear frequently in coding interviews.
โ What is an Array?
An array is a fixed-size, indexed collection of elements of the same type.
โจ Declaring & Initializing Arrays
// Declare and allocate memory
int[] numbers = new int[5];
// Declare and assign values
int[] scores = new int[] { 90, 85, 78, 92, 88 };
// Short-hand initialization
string[] names = { "Alice", "Bob", "Charlie" };
๐ Accessing and Updating Elements
int first = scores[0];
scores[2] = 80;
int last = scores[scores.Length - 1];
๐ Looping Through Arrays
// Using for loop
for (int i = 0; i < scores.Length; i++) {
Console.WriteLine(scores[i]);
}
// Using foreach loop
foreach (int score in scores) {
Console.WriteLine(score);
}
๐ง Useful Array Operations
Array.Sort(scores); // Sort ascending
Array.Reverse(scores); // Reverse array
int index = Array.IndexOf(scores, 92); // Find index of 92
๐ง Common Use Cases
Use Case | Description |
---|---|
Fixed-size data storage | e.g., Top 5 student scores |
Indexed logic | Two pointers, prefix sum, etc. |
Brute force comparisons | e.g., nested loops for pair matching |
๐งช Interview Example: Two Sum (Brute Force)
public int[] TwoSum(int[] nums, int target) {
for (int i = 0; i < nums.Length; i++) {
for (int j = i + 1; j < nums.Length; j++) {
if (nums[i] + nums[j] == target)
return new int[] { i, j };
}
}
return new int[] { -1, -1 };
}
๐ Summary
Feature | Syntax Example |
---|---|
Declare | int[] arr = new int[5]; |
Access |
arr[0] , arr[arr.Length - 1]
|
Update | arr[2] = 100; |
Loop |
for or foreach
|
Sort/Reverse |
Array.Sort(arr) , Array.Reverse()
|
Stay tuned for the next post where we tackle HashSet and use it to solve unique element problems efficiently.
Top comments (1)
try this if you get stuck during the interview. its an AI co-pilot that solves the questions for you so you can focus on the more important part of the interview, the communication part. its also a really good study tool: ghostengineer.com