Invalid Transactions

Starting today, I will try to solve mostly medium level LC questions as I’ve solved about 75% of easy questions. This one seems to be quite easy as it only involves straightforward logic.

class Solution {
    fun invalidTransactions(transactions: Array<String>): List<String> {
        if(transactions.isNullOrEmpty()) return emptyList<String>()
        val output = HashSet<String>()
        
        // put all transactions in collection
        var allTx = mutableListOf<Transaction>()
        transactions.forEach { allTx.add(Transaction.fromString(it)) }
        
        // then for each tx, find any other tx which meets the criteria
        allTx.forEach { current ->
            if(current.amount > 1000) output.add(current.toString())
            else 
            if(allTx.any { 
                it != current && it.name == current.name && it.city != current.city && Math.abs(it.time - current.time) <= 60
            }) output.add(current.toString())
        }
        
        return output.toList()
    }
    
    data class Transaction(val name: String, val time: Int, val amount: Int, val city: String) {
        companion object {
            fun fromString(value: String) : Transaction {
                val parts = value.split(",")
                return Transaction(parts[0], parts[1].toInt(), parts[2].toInt(), parts[3])
            }    
        }
        
        override fun toString() : String {
            return "${this.name},${this.time},${this.amount},${this.city}"
        }
    }
}
Runtime: 272 ms, faster than 94.44% of Kotlin online submissions for Invalid Transactions.
Memory Usage: 38.7 MB, less than 100.00% of Kotlin online submissions for Invalid Transactions.

First, we store all transactions in a collection so that later, we can check each transaction against all other transactions and if any of the comparison matches any of the criteria, then we add the current transaction to the output.

comments powered by Disqus