What is an Array and a String?
Solution and explanation
Array
An array stores elements of the same type in contiguous (adjacent) memory locations, accessed by an index starting at 0. Because the address of element i is base + i × size, reading any element takes O(1).
index: 0 1 2 3 4
value: [ 12 | 45 | 7 | 23 | 56 ]
address: 1000 1004 1008 1012 1016 (4-byte ints)
int[] marks = {12, 45, 7, 23, 56};
System.out.println(marks[2]); // 7 (O(1) access)
marks[2] = 70; // O(1) update
int sum = 0;
for (int m : marks) sum += m; // O(n) traversal
System.out.println(sum); // 206
Operation complexity
- Access/update by index: O(1).
- Search unsorted: O(n). Search sorted (binary search): O(log n).
- Insert/delete at the end of a dynamic array (ArrayList): amortised O(1).
- Insert/delete at the start or middle: O(n), because elements shift.
Static vs dynamic arrays
Java arrays have a fixed size. ArrayList grows by allocating a larger array (about 1.5×) and copying, which is why appends are amortised O(1).
String
A string is a sequence of characters. In Java, String is immutable: every "modification" creates a new object. Use StringBuilder when building strings in a loop.
String s = "ascendia";
System.out.println(s.length()); // 8
System.out.println(s.charAt(0)); // a
System.out.println(s.substring(0, 3)); // asc
System.out.println(s.indexOf("end")); // 2
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i).append(',');
System.out.println(sb); // 0,1,2,
Note: s1 == s2 compares references; always compare string content with equals().
Common techniques for array/string problems
- Two pointers (from both ends or slow/fast).
- Prefix sums for range totals.
- Sliding window for subarrays/substrings.
- Hashing (HashMap/HashSet) for counts and lookups.
- Sorting first to simplify the problem.
Advantages and disadvantages
- O(1) random access, cache-friendly, low memory overhead.
- Fixed size (static arrays) and costly insertion/deletion in the middle.
