Skip to content

Instantly share code, notes, and snippets.

@yjunechoe
Created February 15, 2025 18:07
Show Gist options
  • Save yjunechoe/b949b6b053495301cc11cd90ab3f0b02 to your computer and use it in GitHub Desktop.
Save yjunechoe/b949b6b053495301cc11cd90ab3f0b02 to your computer and use it in GitHub Desktop.
Leetcode twosum problem in R
twosum <- function(nums, target) {
cur_i <- 1
nxt_i <- cur_i + 1
while(cur_i != length(nums)) {
thesum <- nums[cur_i] + nums[cur_i + 1]
if (thesum == target) {
return(c(cur_i, nxt_i))
}
if (nxt_i == length(nums)) {
cur_i <- cur_i + 1
nxt_i <- cur_i + 1
} else {
nxt_i <- nxt_i + 1
}
}
return(NULL)
}
# Tests
library(testthat)
expect_identical(
twosum(c(2, 7, 11, 15), 9),
c(1, 2)
)
expect_identical(
twosum(c(3, 2, 4), 6),
c(2, 3)
)
expect_identical(
twosum(c(3, 3), 6),
c(1, 2)
)
@yjunechoe
Copy link
Author

yjunechoe commented Feb 15, 2025

Last stone weight

laststoneweight <- function(stones) {
  while (length(stones) > 1) {
    sorted_stones <- rev(sort(stones))
    difference <- abs(diff(sorted_stones[1:2]))
    first_i <- which(stones == sorted_stones[1])[1]
    second_i <- which(stones == sorted_stones[2])[1]
    if (difference == 0) {
      stones <- stones[-c(first_i, second_i)]
    } else {
      stones[first_i] <- difference
      stones <- stones[-second_i]
    }
  }
  stones
}

# Tests
library(testthat)
expect_identical(
  laststoneweight(c(2, 7, 4, 1, 8, 1)),
  c(1)
)
expect_identical(
  laststoneweight(c(1)),
  c(1)
)

@yjunechoe
Copy link
Author

Longest common prefix:

longestcommonprefix <- function(strs) {
  shortest <- strs[which.min(nchar(strs))]
  cur <- 0
  while (cur < nchar(shortest)) {
    next_prefix <- substr(shortest, 1, cur + 1)
    prefix_is_shared <- all(
      sapply(strs, \(str) substr(str, 1, cur + 1) == next_prefix)
    )
    if (!prefix_is_shared) {
      break
    }
    cur <- cur + 1
  }
  shared_prefix <- substr(shortest, 1, cur)
  shared_prefix
}

# Tests
library(testthat)
expect_identical(
  longestcommonprefix(c("flower","flow","flight")),
  "fl"
)
expect_identical(
  longestcommonprefix(c("dog","racecar","car")),
  ""
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment