Data Analysis | AP - Wyatt's Notes
Data Structures (CED Unit 3, AP CS A)
Section titled “Data Structures (CED Unit 3, AP CS A)”Arrays
Section titled “Arrays”A fixed-size, ordered collection of elements of the same type.
Java:
int[] scores = new int[10];int[] nums = {3, 1, 4, 1, 5, 9};- Index from
0tolength - 1. - access by index.
- search (unsorted), search (sorted, binary search).
- Insertion and deletion are (requires shifting elements).
Common pitfalls with arrays:
ArrayIndexOutOfBoundsExceptionwhen accessing an index outside the valid range.- The length of a Java array is fixed after creation.
- Java initializes all array elements to default values: 0 for integers,
nullfor objects.
Traversing and processing:
int[] scores = {85, 92, 78, 95, 88};int sum = 0;int max = scores[0];int min = scores[0];for (int s : scores) { sum += s; if (s > max) max = s; if (s < min) min = s;}double average = (double) sum / scores.length;ArrayList (AP CS A)
Section titled “ArrayList (AP CS A)”A resizable array from the java.util package.
ArrayList<String> names = new ArrayList<String>();names.add("Alice");names.add("Bob");names.add(1, "Charlie");String s = names.get(0);names.set(0, "Alicia");names.remove(2);int size = names.size();boolean found = names.contains("Bob");int index = names.indexOf("Alice");Array vs ArrayList:
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic (resizable) |
| Primitives | Yes | No (use wrapper classes) |
length/size | arr.length | list.size() |
| Access | arr[i] | list.get(i) |
| Modify | arr[i] = val | list.set(i, val) |
| Add element | Not possible | list.add(val) |
2D Arrays
Section titled “2D Arrays”Arrays of arrays, useful for grids, matrices, and tables.
Java:
int[][] grid = new int[3][4];int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};grid[row][col]: row-major order.grid.length: number of rows.grid[0].length: number of columns.
for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[r].length; c++) { System.out.print(grid[r][c] + " "); } System.out.println();}Data Analysis Concepts (CED Unit 3)
Section titled “Data Analysis Concepts (CED Unit 3)”Processing Data
Section titled “Processing Data”- Filtering: Selecting data that meets criteria.
- Mapping/Transforming: Applying a function to each element.
- Reducing/Aggregating: Combining data into a summary (sum, average, max, min).
- Sorting: Arranging data in a specific order.
Finding Minimum and Maximum
Section titled “Finding Minimum and Maximum”PROCEDURE findMin(list){ min <- list[1] FOR EACH item IN list { IF (item < min) { min <- item } } RETURN(min)}Proof of correctness. The algorithm maintains the invariant: “min is the smallest element among All elements seen so far.” Initially, min = list[1], true. At each step, if the new Element is smaller, we update min. By induction, after all elements, min is the smallest.
Computing the Average
Section titled “Computing the Average”PROCEDURE average(list){ sum <- 0 FOR EACH item IN list { sum <- sum + item } RETURN(sum / LENGTH(list))}Edge case. If the list is empty, division by zero occurs. A robust implementation should check For this.
Mode (Most Frequent Element)
Section titled “Mode (Most Frequent Element)”PROCEDURE findMode(list){ mode <- list[1] modeCount <- 1 FOR i <- 2 TO LENGTH(list) { count <- 1 FOR j <- 1 TO i - 1 { IF (list[j] = list[i]) { count <- count + 1 } } IF (count > modeCount) { modeCount <- count mode <- list[i] } } RETURN(mode)}Time complexity: . A more efficient approach sorts the list first.
Privacy and Security (CED Unit 4)
Section titled “Privacy and Security (CED Unit 4)”Data Privacy
Section titled “Data Privacy”- Personally identifiable information (PII): Information that can identify an individual.
- Anonymization: Removing PII from datasets before analysis or sharing.
- Metadata: Data about data (e.g., timestamps, GPS coordinates in photos).
Encryption
Section titled “Encryption”- Symmetric encryption: Same key for encryption and decryption (e.g., AES). Fast.
- Asymmetric encryption: Public key for encryption, private key for decryption (e.g., RSA). Slower, but no need to share a secret key.
- Hashing: One-way function that produces a fixed-size output. Not encryption.
Salting passwords. A salt is a random string added to the password before hashing. This prevents Rainbow table attacks.
Digital Certificates and PKI
Section titled “Digital Certificates and PKI”- Digital certificates bind a public key to an identity, verified by a certificate authority (CA).
- PKI manages the creation, distribution, and revocation of digital certificates.
Additional Topics
Section titled “Additional Topics”Searching in a Sorted ArrayList (AP CS A)
Section titled “Searching in a Sorted ArrayList (AP CS A)”public static int binarySearchList(ArrayList<Integer> list, int target) { int low = 0; int high = list.size() - 1; while (low <= high) { int mid = low + (high - low) / 2; int cmp = Integer.compare(list.get(mid), target); if (cmp == 0) return mid; else if (cmp < 0) low = mid + 1; else high = mid - 1; } return -1;}For-Each Loop with ArrayList
Section titled “For-Each Loop with ArrayList”ArrayList<String> names = new ArrayList<>();names.add("Alice");names.add("Bob");names.add("Charlie");
for (String name : names) { System.out.println(name);}Modifying ArrayList During Iteration
Section titled “Modifying ArrayList During Iteration”for (int i = names.size() - 1; i >= 0; i--) { if (names.get(i).length() < 3) { names.remove(i); }}The Comparable Interface (AP CS A)
Section titled “The Comparable Interface (AP CS A)”public class Student implements Comparable<Student> { private String name; private int grade;
public int compareTo(Student other) { return this.grade - other.grade; }}Big-O Analysis of ArrayList Operations
Section titled “Big-O Analysis of ArrayList Operations”| Operation | Average | Worst |
|---|---|---|
get(i) | ||
add(item) | ||
add(i, item) | ||
remove(i) | ||
remove(Object) | ||
set(i, item) | ||
contains(Object) | ||
indexOf(Object) |
String Algorithms
Section titled “String Algorithms”Reversing a string:
public static String reverse(String s) { String result = ""; for (int i = s.length() - 1; i >= 0; i--) { result += s.charAt(i); } return result;}Time complexity: because string concatenation creates a new object each time. A more Efficient approach uses StringBuilder for .
Counting character frequency:
public static int[] charFrequency(String s) { int[] freq = new int[26]; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= "a' && c <= 'z') { freq[c - 'a']++; } } return freq;}Time complexity: .
Privacy Laws and Regulations
Section titled “Privacy Laws and Regulations”- GDPR (EU): Right to access, right to be forgotten, data portability.
- CCPA (California): Right to know, right to delete, right to opt out.
- COPPA (US): Protects children under 13 online.
Data Breaches
Section titled “Data Breaches”A data breach is an incident where sensitive data is accessed without authorisation. Consequences Include identity theft, financial loss, and reputational damage.
Prevention strategies:
- Encrypt sensitive data at rest and in transit.
- Implement access controls (principle of least privilege).
- Regular security audits and penetration testing.
- Employee training on security awareness.
- Monitor for unusual access patterns.
The Math class in Java (AP CS A)
Section titled “The Math class in Java (AP CS A)”int abs = Math.abs(-5); // 5int max = Math.max(3, 7); // 7int min = Math.min(3, 7); // 3double sqrt = Math.sqrt(16.0); // 4.0int random = (int)(Math.random() * 10); // 0-9int pow = (int)Math.pow(2, 10); // 1024Wrapper Classes and Autoboxing (AP CS A)
Section titled “Wrapper Classes and Autoboxing (AP CS A)”| Primitive | Wrapper |
|---|---|
| int | Integer |
| double | Double |
| boolean | Boolean |
| char | Character |
ArrayList<Integer> list = new ArrayList<>();list.add(5); // autoboxing: int -> Integerint value = list.get(0); // unboxing: Integer -> intInteger Division and Type Casting
Section titled “Integer Division and Type Casting”int a = 5 / 2; // 2 (integer division)double b = 5.0 / 2; // 2.5 (double division)int c = (int) 2.9; // 2 (truncation)double d = (double) 5 / 2; // 2.5Caution: Always cast to
doublebefore division when you need a decimal result.
Practice Questions
Section titled “Practice Questions”Write a Java method that finds and returns the mode (most frequent element) in an array of integers.
Write a Java method
isSorted(int[] arr)that returnstrueif the array is sorted in ascending order.Given a 2D array representing a seating chart (0 = empty, 1 = occupied), write a method that counts the number of occupied seats.
Write pseudocode for a procedure that removes all occurrences of a given value from a list.
Explain the difference between symmetric and asymmetric encryption.
Write a Java method that takes a string and returns a new string with all vowels removed.
Given an
ArrayListof student names, write code to find all names that start with “A”.Explain why
==should not be used to compare String objects in Java.Write a Java method that takes a 2D array and returns the sum of the main diagonal elements.
Explain what a salt is and why it is important for password security.
Write pseudocode for a procedure that finds the median value in a sorted list.
Explain the difference between anonymization and encryption.
Write a Java method
isPalindrome(String s)that ignores case and non-alphanumeric characters.Explain the difference between
ArrayIndexOutOfBoundsExceptionandNullPointerException. Give an example of code that causes each.Write a Java method that finds the two largest values in an array in a single pass.
Write pseudocode for a procedure
mergeSorted(list1, list2)that merges two sorted lists into one sorted list.Explain what metadata is and give two examples where metadata could reveal sensitive information.
Write a Java method that counts the frequency of each character in a string and returns the results in a Map.
Explain the difference between an array and an ArrayList. Give three scenarios where you would use each.
Write a Java method that takes a 2D array and returns the transpose of the matrix. What is the time complexity?
Iterating Over 2D Arrays
Section titled “Iterating Over 2D Arrays”Row-major traversal:
for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[r].length; c++) { System.out.print(grid[r][c] + " "); } System.out.println();}Column-major traversal:
for (int c = 0; c < grid[0].length; c++) { for (int r = 0; r < grid.length; r++) { System.out.print(grid[r][c] + " "); } System.out.println();}Finding Maximum in a 2D Array
Section titled “Finding Maximum in a 2D Array”public static int findMax2D(int[][] grid) { int max = grid[0][0]; for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[r].length; c++) { if (grid[r][c] > max) { max = grid[r][c]; } } } return max;}Time complexity: where is rows and is columns.
Jagged Arrays (AP CS A)
Section titled “Jagged Arrays (AP CS A)”A jagged array is a 2D array where rows have different lengths.
int[][] jagged = { {1, 2, 3}, {4, 5}, {6, 7, 8, 9}};Iterating over a jagged array: Use grid[r].length for each row, not grid[0].length.
Enhanced For Loop with 2D Arrays
Section titled “Enhanced For Loop with 2D Arrays”for (int[] row : grid) { for (int val : row) { System.out.print(val + " "); } System.out.println();}The Arrays Class (AP CS A)
Section titled “The Arrays Class (AP CS A)”import java.util.Arrays;
int[] arr = {5, 3, 8, 1};Arrays.sort(arr); // [1, 3, 5, 8]int idx = Arrays.binarySearch(arr, 5); // 2String s = Arrays.toString(arr); // "[1, 3, 5, 8]"Common String Methods in Detail
Section titled “Common String Methods in Detail”String s = "Hello, World!";
s.length() // 13s.substring(7) // "World!"s.substring(0, 5) // "Hello"s.indexOf("World") // 7s.charAt(1) // 'e's.equals("hello, world!") // false (case-sensitive)s.equalsIgnoreCase("hello, world!") // trues.compareTo("Hello") // > 0 (positive)s.toUpperCase() // "HELLO, WORLD!"s.toLowerCase() // "hello, world!"s.trim() // removes leading/trailing whitespaces.replace("World", "CS") // "Hello, CS!"String concatenation pitfall:
String result = "";for (int i = 0; i < 10000; i++) { result += "x"; // Creates 10,000 String objects! O(n^2)}// Better:StringBuilder sb = new StringBuilder();for (int i = 0; i < 10000; i++) { sb.append("x"); // O(n)}String result = sb.toString();Comparing Data with Scatter Plots
Section titled “Comparing Data with Scatter Plots”Scatter plots are used to visualise the relationship between two variables.
- Positive correlation: As x increases, y increases.
- Negative correlation: As x increases, y decreases.
- No correlation: No visible pattern.
Correlation does not imply causation. Two variables may be correlated due to a confounding Variable, not because one causes the other.
Data Cleaning
Section titled “Data Cleaning”Real-world data is often messy and requires cleaning before analysis:
- Handling missing values: Remove records, impute with mean/median, or flag as unknown.
- Removing duplicates: Prevents double-counting in analysis.
- Correcting formats: Standardising date formats, fixing inconsistent capitalisation.
- Outlier detection: Identifying and deciding whether to include or exclude extreme values.
Common Pitfalls
Section titled “Common Pitfalls”- Using
==to compare strings. Always use.equals()for content comparison. - Off-by-one errors with
substring.substring(a, b)includes indexabut excludesb. - Confusing
ArrayListsize with array length.list.size()vsarr.length. - Forgetting that strings are immutable. Methods return new strings; they do not modify the original.
- Not handling empty arrays or null inputs.
- Confusing row and column indices in 2D arrays.
grid[row][col]. - Integer division in Java.
5 / 2equals2Not2.5. Cast todouble. - Confusing
substringparameters across languages. Javasubstring(1, 4)returns chars at indices 1, 2, 3.
Additional Topics
Section titled “Additional Topics”Searching in a Sorted ArrayList (AP CS A)
Section titled “Searching in a Sorted ArrayList (AP CS A)”public static int binarySearchList(ArrayList<Integer> list, int target) { int low = 0; int high = list.size() - 1; while (low <= high) { int mid = low + (high - low) / 2; int cmp = Integer.compare(list.get(mid), target); if (cmp == 0) return mid; else if (cmp < 0) low = mid + 1; else high = mid - 1; } return -1;}For-Each Loop with ArrayList
Section titled “For-Each Loop with ArrayList”ArrayList<String> names = new ArrayList<>();names.add("Alice");names.add("Bob");names.add("Charlie");
for (String name : names) { System.out.println(name);}Modifying ArrayList During Iteration
Section titled “Modifying ArrayList During Iteration”Intuition
Section titled “Intuition”The digital world runs on algorithms and data. From search engines to social media, software systems process information through carefully designed procedures. Computer science teaches us to think systematically about problems, design efficient solutions, and understand the technologies that shape modern life. These skills are essential for innovation in every field.