Skip to content

Latest commit

 

History

History
296 lines (229 loc) · 8.95 KB

File metadata and controls

296 lines (229 loc) · 8.95 KB

Multi-Language Syntax Cheatsheet

HackerRank algorithm solutions reference for C, C++, Go, JavaScript, PHP, Python, R, and Rust

Table of Contents


Array Size

Language Function/Syntax Example
Python len() len(arr)
PHP count() count($arr)
JavaScript .length arr.length
Go len() len(arr)
C manual / sizeof sizeof(arr) / sizeof(arr[0])
C++ .size() or sizeof arr.size() (vector)
Rust .len() arr.len()
R length() length(arr)

Array Declaration

Declaring [0, 0, 0] in all 8 languages:

Language Syntax
Python arr = [0, 0, 0]
PHP $arr = [0, 0, 0];
JavaScript const arr = [0, 0, 0];
Go arr := []int{0, 0, 0}
C int arr[] = {0, 0, 0};
C++ vector<int> arr = {0, 0, 0};
Rust let arr = vec![0, 0, 0];
R arr <- c(0, 0, 0)

Notes:

  • Go: []int is a slice. For fixed array: arr := [3]int{0, 0, 0}
  • C++: Requires #include <vector>. For fixed array: int arr[] = {0, 0, 0};
  • Rust: vec! is a dynamic vector. For fixed array: let arr = [0, 0, 0];
  • R: c() combines values into a vector. R has no traditional arrays.

For Loops

Index-Based Loops

Language For Loop Syntax Index var Keyword Access
Python for i in range(len(arr)): i in arr[i]
PHP for ($i = 0; $i < count($arr); $i++) $i $arr[$i]
JavaScript for (let i = 0; i < arr.length; i++) i arr[i]
Go for i := 0; i < len(arr); i++ i arr[i]
C for (int i = 0; i < n; i++) i arr[i]
C++ for (int i = 0; i < arr.size(); i++) i arr[i]
Rust for i in 0..arr.len() i in arr[i]
R ⚠️ for (i in 1:length(arr)) i in arr[i]

⚠️ R starts from 1, not 0! 1:length(arr) goes from 1 to n, and arr[1] is the first element.

Direct Element Loops

Language Direct Element Loop Access
Python for i in arr: i
PHP foreach ($arr as $i) $i
JavaScript for (const i of arr) i
Go for _, i := range arr i
C++ for (auto i : arr) i
Rust for i in arr.iter() i
R for (i in arr) i
C ❌ not supported

Notes:

  • Go: _ ignores the index since range returns both index and value
  • JavaScript: use of not in (in gives you keys/indices)
  • C: has no direct iteration — must use index-based loops
  • Rust: Ranges in rust only go forward so use .rev()

Rust Range

Pattern Code Output
Up (exclusive) 0..5 0, 1, 2, 3, 4
Up (inclusive) 0..=5 0, 1, 2, 3, 4, 5
Down (0..5).rev() 4, 3, 2, 1, 0
Down (inclusive) (1..=n).rev() n, n-1, ..., 1

Note: Rust ranges only go forward. Use .rev() to reverse.

for i in (0..n).rev() {
    // n-1, n-2, ..., 0
}

JavaScript in vs of

JS Syntax Returns Python equivalent
for (i in arr) indices/keys for i in range(len(arr))
for (i of arr) values for i in arr
JS PHP equivalent
for (i of arr) foreach ($arr as $v) — value
for (i in arr) foreach ($arr as $k => $v) — key only

Rust Iterator Dereferencing

.iter() gives references (&i32), so dereference with *:

for i in arr.iter() {
    if *i > 0 {           // dereference with *
        counters[0] += 1;
    }
}

Or dereference in the loop declaration:

for &i in arr.iter() {   // &i pattern extracts the value
    if i > 0 {
        counters[0] += 1;
    }
}
Syntax i is Compare with
for i in arr.iter() &i32 (reference) *i > 0
for &i in arr.iter() i32 (value) i > 0

Increment & Decrement

Language Increment Decrement Notes
Python i += 1 i -= 1 No ++ / --
PHP $i++ or ++$i $i-- or --$i Both pre/post work
JavaScript i++ or ++i i-- or --i Both pre/post work
Go i++ i-- Post only, no ++i, statement only
C i++ or ++i i-- or --i Both pre/post work
C++ i++ or ++i i-- or --i Both pre/post work
Rust i += 1 i -= 1 No ++ / --
R i <- i + 1 i <- i - 1 No ++ / --, no +=

Python increment:

❌ Won't work ✅ Works
++i i += 1
i++ i += 1
--i i -= 1

Summary:

  • ❌ No ++: Python, Rust, R
  • ⚠️ Post only: Go (i++ but not ++i)
  • ✅ Full support: PHP, JavaScript, C, C++

Float Division & Casting

Language Need to cast Example
Python None a / b
PHP None $a / $b
JavaScript None a / b
R None a / b
C One (float)a / b
C++ One (float)a / b
Go Both float64(a) / float64(b)
Rust Both a as f64 / b as f64

💡 Why cast both in Go/Rust? Go and Rust are strictly typed — both operands must be the same type for any operation. No implicit conversion.

💡 Precision: Use f64 (Rust) or float64 (Go) for precision. f32/float32 works but less common.


Print to Output

Basic Print

Language Syntax Notes
Python print("hello") Adds newline
PHP echo "hello"; No newline
JavaScript console.log("hello") Adds newline
Go fmt.Println("hello") Adds newline
C printf("hello\n"); Manual newline
C++ cout << "hello" << endl; endl = newline
Rust println!("hello"); Adds newline
R cat("hello", "\n") Manual newline

Print Without Newline

Language Syntax
Python print("hello", end="")
PHP echo "hello";
JavaScript process.stdout.write("hello")
Go fmt.Print("hello")
C printf("hello");
C++ cout << "hello";
Rust print!("hello");
R cat("hello")

Print with Variables

Language Syntax
Python print(f"value: {x}")
PHP echo "value: $x";
JavaScript console.log(`value: ${x}`)
Go fmt.Printf("value: %d\n", x)
C printf("value: %d\n", x);
C++ cout << "value: " << x << endl;
Rust println!("value: {}", x);
R cat("value:", x, "\n")

R print vs cat

Function Output for "hello"
print("hello") [1] "hello"
cat("hello", "\n") hello

💡 Use cat() for clean CLI output in R. print() shows index and quotes.


Format Numbers

Format a number with 6 decimal places:

Language Syntax
Python f"{result:.6f}" or "%.6f" % result
PHP number_format($result, 6, '.', '')
JavaScript result.toFixed(6)
Go fmt.Sprintf("%.6f", result)
C printf("%.6f", result);
C++ cout << fixed << setprecision(6) << result;
Rust format!("{:.6}", result)
R sprintf("%.6f", result)

💡 The pattern %.6f is universal across C-family languages — 6 controls decimal places, f means floating-point.


Required Imports

Language Import needed
Go import "fmt"
C++ #include <iostream> + using namespace std;
C++ (vector) #include <vector>
C++ (precision) #include <iomanip>

Resources


License

MIT